use crate::AnalysisResult;

pub fn render(result: &AnalysisResult) -> String {
    let matched = result
        .variants
        .iter()
        .filter(|v| v.matched.is_some())
        .count();
    let unmatched = result.variants.len() - matched;

    let variants_json: Vec<serde_json::Value> = result
        .variants
        .iter()
        .map(|v| {
            let mut obj = serde_json::json!({
                "input_id": v.input.id,
                "gene": v.input.gene,
                "confidence": v.confidence,
                "risk_level": v.risk_level,
            });

            if let Some(ref m) = v.matched {
                obj["matched"] = serde_json::json!({
                    "id": m.id,
                    "gene": m.gene,
                    "variant": m.variant_name,
                    "category": m.category,
                    "pathogenicity": m.pathogenicity,
                    "actionable": m.actionable,
                    "clinical_note": m.clinical_note,
                    "sources": m.sources,
                });
            }

            if !v.actions.is_empty() {
                obj["actions"] = serde_json::json!(v.actions);
            }

            if let Some(ref pgx) = v.pgx {
                obj["pharmacogenomics"] = serde_json::json!({
                    "gene": pgx.gene,
                    "phenotype": pgx.phenotype,
                    "affected_drugs": pgx.affected_drugs,
                    "recommendation": pgx.recommendation,
                });
            }

            obj
        })
        .collect();

    serde_json::json!({
        "version": "1",
        "status": "success",
        "data": {
            "variants": variants_json,
        },
        "metadata": {
            "total_input": result.total_input,
            "matched": matched,
            "unmatched": unmatched,
        }
    })
    .to_string()
}

pub fn render_error(msg: &str) -> String {
    serde_json::json!({
        "version": "1",
        "status": "error",
        "error": msg,
    })
    .to_string()
}
