//! Helper functions for steme-pharma CLI.

use ed25519_dalek::SigningKey;
use stemedb_core::types::{ObjectValue, SourceClass};
use stemedb_ontology::{client::StemeClient, pharma::extractors::MedicalClaim};

/// Ingest mock conflict data to demonstrate SkepticLens.
pub async fn ingest_mock_conflicts(
    client: &StemeClient,
    signing_key: &SigningKey,
    agent_id: [u8; 32],
    hlc: &uhlc::HLC,
) -> (usize, usize) {
    let mock_claims = vec![
        // Mock Trial A: Higher HbA1c reduction than FDA label
        MedicalClaim::new(
            "Semaglutide:Type2Diabetes",
            "hba1c_change_percent",
            ObjectValue::Number(-1.5),
        )
        .with_confidence(0.90)
        .with_source_class(SourceClass::Clinical)
        .with_source_url("https://clinicaltrials.gov/study/NCT_MOCK_001")
        .with_source_section("Primary Endpoint")
        .with_quote("Mean HbA1c change from baseline: -1.5% (95% CI: -1.7 to -1.3)"),
        // Mock Trial B: Lower HbA1c reduction
        MedicalClaim::new(
            "Semaglutide:Type2Diabetes",
            "hba1c_change_percent",
            ObjectValue::Number(-0.8),
        )
        .with_confidence(0.85)
        .with_source_class(SourceClass::Clinical)
        .with_source_url("https://clinicaltrials.gov/study/NCT_MOCK_002")
        .with_source_section("Secondary Endpoint")
        .with_quote("Mean HbA1c change from baseline: -0.8% in intention-to-treat population"),
        // Anecdotal: Patient report
        MedicalClaim::new(
            "Semaglutide:Type2Diabetes",
            "hba1c_change_percent",
            ObjectValue::Number(-0.3),
        )
        .with_confidence(0.50)
        .with_source_class(SourceClass::Anecdotal)
        .with_source_url("https://reddit.com/r/diabetes/comments/mock_thread")
        .with_source_section("User Report")
        .with_quote("My A1C only dropped by 0.3 points after 3 months"),
        // Mock Trial: Different nausea rate
        MedicalClaim::new("Semaglutide", "nausea_rate", ObjectValue::Number(0.25))
            .with_confidence(0.88)
            .with_source_class(SourceClass::Clinical)
            .with_source_url("https://clinicaltrials.gov/study/NCT_MOCK_003")
            .with_source_section("Adverse Events")
            .with_quote("Nausea reported in 25% of participants (vs 12% placebo)"),
        // Mock Observational: Real-world nausea rate
        MedicalClaim::new("Semaglutide", "nausea_rate", ObjectValue::Number(0.38))
            .with_confidence(0.75)
            .with_source_class(SourceClass::Observational)
            .with_source_url("https://example.com/real-world-evidence/semaglutide")
            .with_source_section("Safety Analysis")
            .with_quote("Nausea occurred in 38% of patients in real-world setting"),
        // Weight loss disagreement
        MedicalClaim::new(
            "Semaglutide:ChronicWeightManagement",
            "weight_loss_percent",
            ObjectValue::Number(-18.5),
        )
        .with_confidence(0.92)
        .with_source_class(SourceClass::Clinical)
        .with_source_url("https://clinicaltrials.gov/study/NCT_MOCK_004")
        .with_source_section("Primary Endpoint")
        .with_quote("Mean weight loss: -18.5% at 68 weeks"),
        MedicalClaim::new(
            "Semaglutide:ChronicWeightManagement",
            "weight_loss_percent",
            ObjectValue::Number(-12.0),
        )
        .with_confidence(0.70)
        .with_source_class(SourceClass::Community)
        .with_source_url("https://patientslikeme.com/treatments/semaglutide/reviews")
        .with_source_section("Patient Reports Aggregated")
        .with_quote("Average reported weight loss: 12% among community members"),
    ];

    let mut ingested = 0usize;
    let mut errors = 0usize;

    for claim in mock_claims {
        let tier = format!("{:?}", claim.source_class);
        let assertion = claim.to_assertion(signing_key, agent_id, hlc);

        match client.assert(&assertion).await {
            Ok(hash) => {
                ingested += 1;
                println!(
                    "  [{}] {} {} = {} -> {}...",
                    tier,
                    claim.subject,
                    claim.predicate,
                    format_value(&claim.value),
                    &hash[..16]
                );
            }
            Err(e) => {
                errors += 1;
                println!("  [ERROR] {} {} -> {}", claim.subject, claim.predicate, e);
            }
        }
    }

    (ingested, errors)
}

/// Format an ObjectValue for display.
pub fn format_value(value: &ObjectValue) -> String {
    match value {
        ObjectValue::Text(s) => {
            if s.len() > 40 {
                format!("\"{}...\"", &s[..37])
            } else {
                format!("\"{}\"", s)
            }
        }
        ObjectValue::Number(n) => format!("{}", n),
        ObjectValue::Boolean(b) => format!("{}", b),
        ObjectValue::Reference(r) => format!("@{}", r),
    }
}
