// Package main demonstrates Episteme's conflict resolution features.
//
// This example shows the "Git for Truth" moment - when agents disagree,
// Episteme shows you the disagreement instead of silently picking a winner.
//
// It demonstrates:
//   - Creating conflicting assertions with different source classes
//   - Using Skeptic to see all competing claims
//   - Using Layered to see per-tier consensus
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/orchard9/stemedb-go/steme"
)

func main() {
	// Setup client with a new keypair
	signer, err := steme.GenerateSigner()
	if err != nil {
		log.Fatalf("Failed to generate signer: %v", err)
	}

	client := steme.NewClient("http://localhost:18180", signer)
	ctx := context.Background()

	fmt.Println("=== Episteme: Conflict Resolution Demo ===")
	fmt.Println()

	// Create conflicting assertions about GLP-1 cardiovascular benefits
	// Different source classes will disagree
	createConflictingAssertions(ctx, client)

	// Wait for ingestion
	fmt.Println("Waiting for ingestion...")
	time.Sleep(500 * time.Millisecond)

	// Demonstrate Skeptic: See all competing claims
	demonstrateSkeptic(ctx, client)

	// Demonstrate Layered: See per-tier consensus
	demonstrateLayered(ctx, client)
}

func createConflictingAssertions(ctx context.Context, client *steme.Client) {
	fmt.Println("Creating conflicting assertions about GLP-1 cardiovascular benefits...")
	fmt.Println()

	// Clinical trial says: YES, cardiovascular benefit (high confidence)
	clinical := steme.NewAssertion("GLP1_Agonists", "cardiovascular_benefit").
		WithBoolean(true).
		WithConfidence(0.92).
		WithLifecycle(steme.LifecycleApproved).
		WithSourceClass(steme.SourceClassClinical).
		WithSourceHash("c11111111111111111111111111111111111111111111111111111111111111c").
		Build()

	hash1, err := client.Assert(ctx, clinical)
	if err != nil {
		log.Printf("Warning: Failed to create clinical assertion: %v", err)
	} else {
		fmt.Printf("  Clinical (Tier 1):   TRUE  -> %s\n", hash1[:16]+"...")
	}

	// Anecdotal report says: NO, cardiovascular issues
	anecdotal := steme.NewAssertion("GLP1_Agonists", "cardiovascular_benefit").
		WithBoolean(false).
		WithConfidence(0.70).
		WithLifecycle(steme.LifecycleProposed).
		WithSourceClass(steme.SourceClassAnecdotal).
		WithSourceHash("a55555555555555555555555555555555555555555555555555555555555555a").
		Build()

	hash2, err := client.Assert(ctx, anecdotal)
	if err != nil {
		log.Printf("Warning: Failed to create anecdotal assertion: %v", err)
	} else {
		fmt.Printf("  Anecdotal (Tier 5):  FALSE -> %s\n", hash2[:16]+"...")
	}

	fmt.Println()
	fmt.Println("Now we have a conflict: Clinical says TRUE, Anecdotal says FALSE.")
	fmt.Println()
}

func demonstrateSkeptic(ctx context.Context, client *steme.Client) {
	fmt.Println("=== Skeptic: Trust but Verify ===")
	fmt.Println()
	fmt.Println("Instead of picking a winner, Skeptic shows ALL competing claims:")
	fmt.Println()

	result, err := client.Skeptic(ctx, steme.SkepticQueryParams{
		Subject:   "GLP1_Agonists",
		Predicate: "cardiovascular_benefit",
	})
	if err != nil {
		log.Printf("Skeptic query failed: %v", err)
		return
	}

	fmt.Printf("  Status:         %s\n", result.Status)
	fmt.Printf("  Conflict Score: %.2f (0=unanimous, 1=chaos)\n", result.ConflictScore)
	fmt.Printf("  Candidates:     %d\n", result.CandidatesCount)
	fmt.Println()

	fmt.Println("  Competing Claims:")
	for i, claim := range result.Claims {
		fmt.Printf("    %d. Value: %v\n", i+1, claim.Value.Value)
		fmt.Printf("       Weight: %.1f%% (%d assertions)\n", claim.WeightShare*100, claim.AssertionCount)
	}
	fmt.Println()

	fmt.Println("  Key Insight: You see the disagreement, not a hidden winner.")
	fmt.Println()
}

func demonstrateLayered(ctx context.Context, client *steme.Client) {
	fmt.Println("=== Layered: Per-Source-Class Resolution ===")
	fmt.Println()
	fmt.Println("Different sources have different authority levels.")
	fmt.Println("Layered shows what each tier says:")
	fmt.Println()

	result, err := client.Layered(ctx, steme.LayeredQueryParams{
		Subject:   "GLP1_Agonists",
		Predicate: "cardiovascular_benefit",
	})
	if err != nil {
		log.Printf("Layered query failed: %v", err)
		return
	}

	for _, tier := range result.Tiers {
		winnerValue := "none"
		if tier.Winner != nil {
			winnerValue = fmt.Sprintf("%v", tier.Winner.Object.Value)
		}
		fmt.Printf("  Tier %d (%s):\n", tier.Tier, tier.SourceClass)
		fmt.Printf("    Winner: %s\n", winnerValue)
		fmt.Printf("    Candidates: %d\n", tier.CandidatesCount)
		fmt.Printf("    Conflict: %.2f\n", tier.ConflictScore)
		fmt.Println()
	}

	if result.OverallWinner != nil {
		fmt.Printf("  Overall Winner: %v (from highest authority tier)\n", result.OverallWinner.Object.Value)
	}
	fmt.Printf("  Cross-Tier Conflict: %.2f\n", result.OverallConflictScore)
	fmt.Println()

	fmt.Println("  Key Insight: Clinical (Tier 1) wins despite Anecdotal (Tier 5) disagreeing.")
	fmt.Println("  The high conflict score warns you that tiers disagree.")
	fmt.Println()
}
