//! OSCAL 1.1 assessment-results — assess our findings against catalog controls.
//!
//! The catalog (domain content) comes from the producer; the **assessment** is
//! ours. This links compliance [`Finding`]s to catalog control-ids and emits a
//! standard OSCAL assessment-results document: an observation per linked finding,
//! and a per-control finding with a `not-satisfied` status. `reviewed-controls`
//! records the full catalog set we considered.
//!
//! Deterministic: stable `uuid5` ids; the caller supplies the assessment
//! timestamp. Pure — no DB, no network.

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid;

use crate::models::finding::{Finding, FindingStatus};

const OSCAL_VERSION: &str = "1.1.2";
/// Same namespace as the catalog exporter, so ids are stable and correlatable.
const NAMESPACE: Uuid = Uuid::from_bytes([
    0x6f, 0x1e, 0x7c, 0x2a, 0x3b, 0x4d, 0x5e, 0x6f, 0x8a, 0x9b, 0x0c, 0x1d, 0x2e, 0x3f, 0x4a, 0x5b,
]);

fn det_uuid(name: &str) -> String {
    Uuid::new_v5(&NAMESPACE, name.as_bytes()).to_string()
}

/// Links findings to the catalog control-ids they provide evidence for.
pub struct ControlLinker {
    cwe_to_controls: HashMap<u32, Vec<String>>,
}

impl ControlLinker {
    /// Build a linker from an explicit CWE → control-id map.
    pub fn new(cwe_to_controls: HashMap<u32, Vec<String>>) -> Self {
        Self { cwe_to_controls }
    }

    /// Seed of CWE → CRA Annex I control mappings (mirrors breakpilot's
    /// `_CWE_TO_REQ`; extend as scanner coverage grows).
    pub fn cra_seed() -> Self {
        let pairs: &[(u32, &str)] = &[
            (798, "cra-ai-8"),
            (259, "cra-ai-8"),
            (1392, "cra-ai-8"),
            (327, "cra-ai-13"),
            (326, "cra-ai-13"),
            (319, "cra-ai-15"),
            (311, "cra-ai-15"),
            (89, "cra-ai-20"),
            (79, "cra-ai-20"),
            (78, "cra-ai-20"),
            (22, "cra-ai-20"),
        ];
        let mut map: HashMap<u32, Vec<String>> = HashMap::new();
        for (cwe, id) in pairs {
            map.entry(*cwe).or_default().push((*id).to_string());
        }
        Self::new(map)
    }

    /// Parse a CWE token such as `"CWE-798"` or `"798"` into its number.
    fn parse_cwe(raw: &str) -> Option<u32> {
        raw.trim_start_matches(|c: char| !c.is_ascii_digit())
            .split(|c: char| !c.is_ascii_digit())
            .next()
            .filter(|s| !s.is_empty())
            .and_then(|s| s.parse().ok())
    }

    /// The control-ids a finding provides evidence for (via its CWE).
    pub fn controls_for(&self, finding: &Finding) -> Vec<String> {
        finding
            .cwe
            .as_deref()
            .and_then(Self::parse_cwe)
            .and_then(|cwe| self.cwe_to_controls.get(&cwe))
            .cloned()
            .unwrap_or_default()
    }
}

/// Build a standard OSCAL assessment-results document from `findings`, using each
/// finding's stamped `control_refs` for control linkage. EVERY non-false-positive
/// finding is emitted as an observation — mapped findings additionally produce a
/// per-control `not-satisfied` finding; **unmapped findings are reported as-is**
/// (an observation carrying their CWE/tool/severity, with no control target) so
/// nothing is lost. `at` is the assessment timestamp.
pub fn assess(findings: &[Finding], at: DateTime<Utc>) -> AssessmentResultsDoc {
    let ts = at.to_rfc3339();

    let mut observations = Vec::new();
    let mut obs_by_control: HashMap<String, Vec<String>> = HashMap::new();
    let mut mapped = 0usize;
    let mut unmapped = 0usize;

    for finding in findings {
        if finding.status == FindingStatus::FalsePositive {
            continue; // flagged tool false positive — excluded from the report
        }
        let obs_uuid = det_uuid(&format!("obs:{}", finding.fingerprint));
        let location = match (&finding.file_path, finding.line_number) {
            (Some(f), Some(l)) => Some(format!("{f}:{l}")),
            (Some(f), None) => Some(f.clone()),
            _ => None,
        };
        let is_mapped = !finding.control_refs.is_empty();
        if is_mapped {
            mapped += 1;
        } else {
            unmapped += 1;
        }
        let mut props = vec![
            ObsProp::new("tool", &finding.scanner),
            ObsProp::new("severity", &finding.severity.to_string()),
            ObsProp::new("mapping", if is_mapped { "mapped" } else { "unmapped" }),
        ];
        if let Some(cwe) = &finding.cwe {
            props.push(ObsProp::new("cwe", cwe));
        }
        observations.push(Observation {
            uuid: obs_uuid.clone(),
            title: finding.title.clone(),
            description: finding.description.clone(),
            methods: vec!["TEST".to_string()],
            collected: ts.clone(),
            props,
            relevant_evidence: vec![RelevantEvidence {
                href: location.map(|l| format!("file://{l}")),
                description: format!("[{}] {}", finding.scanner, finding.title),
            }],
        });
        for control_id in &finding.control_refs {
            obs_by_control
                .entry(control_id.clone())
                .or_default()
                .push(obs_uuid.clone());
        }
    }

    let mut hit_controls: Vec<&String> = obs_by_control.keys().collect();
    hit_controls.sort();
    let ar_findings: Vec<ArFinding> = hit_controls
        .iter()
        .map(|control_id| ArFinding {
            uuid: det_uuid(&format!("finding:{control_id}")),
            title: format!("Findings affect {control_id}"),
            target: FindingTarget {
                target_type: "statement-id".to_string(),
                target_id: format!("{control_id}_smt"),
                status: TargetStatus {
                    state: "not-satisfied".to_string(),
                },
            },
            related_observations: obs_by_control[*control_id]
                .iter()
                .map(|u| RelatedObservation {
                    observation_uuid: u.clone(),
                })
                .collect(),
        })
        .collect();

    let include_controls: Vec<SelectControlById> = hit_controls
        .iter()
        .map(|c| SelectControlById {
            control_id: (*c).clone(),
        })
        .collect();

    let result = ArResult {
        uuid: det_uuid("result:cra"),
        title: "Automated code-compliance assessment".to_string(),
        description: format!(
            "{} observation(s): {mapped} control-linked, {unmapped} unmapped (as-is); {} control(s) affected",
            observations.len(),
            include_controls.len()
        ),
        start: ts.clone(),
        reviewed_controls: ReviewedControls {
            control_selections: vec![ControlSelection { include_controls }],
        },
        observations,
        findings: ar_findings,
    };

    AssessmentResultsDoc {
        assessment_results: AssessmentResults {
            uuid: det_uuid("assessment-results:cra"),
            metadata: ArMetadata {
                title: "Compliance scanner — OSCAL assessment results".to_string(),
                last_modified: ts,
                version: "1.0.0".to_string(),
                oscal_version: OSCAL_VERSION.to_string(),
            },
            import_ap: ImportAp {
                href: "#cra-annex-i".to_string(),
            },
            results: vec![result],
        },
    }
}

// ── OSCAL assessment-results document (serialise) ────────────────────────────

/// The root OSCAL assessment-results document.
#[derive(Debug, Clone, Serialize)]
pub struct AssessmentResultsDoc {
    #[serde(rename = "assessment-results")]
    pub assessment_results: AssessmentResults,
}

#[derive(Debug, Clone, Serialize)]
pub struct AssessmentResults {
    pub uuid: String,
    pub metadata: ArMetadata,
    #[serde(rename = "import-ap")]
    pub import_ap: ImportAp,
    pub results: Vec<ArResult>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArMetadata {
    pub title: String,
    #[serde(rename = "last-modified")]
    pub last_modified: String,
    pub version: String,
    #[serde(rename = "oscal-version")]
    pub oscal_version: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct ImportAp {
    pub href: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArResult {
    pub uuid: String,
    pub title: String,
    pub description: String,
    pub start: String,
    #[serde(rename = "reviewed-controls")]
    pub reviewed_controls: ReviewedControls,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub observations: Vec<Observation>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub findings: Vec<ArFinding>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ReviewedControls {
    #[serde(rename = "control-selections")]
    pub control_selections: Vec<ControlSelection>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ControlSelection {
    #[serde(rename = "include-controls", skip_serializing_if = "Vec::is_empty")]
    pub include_controls: Vec<SelectControlById>,
}

#[derive(Debug, Clone, Serialize)]
pub struct SelectControlById {
    #[serde(rename = "control-id")]
    pub control_id: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct Observation {
    pub uuid: String,
    pub title: String,
    pub description: String,
    pub methods: Vec<String>,
    pub collected: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub props: Vec<ObsProp>,
    #[serde(rename = "relevant-evidence", skip_serializing_if = "Vec::is_empty")]
    pub relevant_evidence: Vec<RelevantEvidence>,
}

/// A name/value observation property (cwe, tool, severity, mapping status). Lets an
/// unmapped finding be reported fully as-is.
#[derive(Debug, Clone, Serialize)]
pub struct ObsProp {
    pub name: String,
    pub value: String,
}

impl ObsProp {
    fn new(name: &str, value: &str) -> Self {
        Self {
            name: name.to_string(),
            value: value.to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RelevantEvidence {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub href: Option<String>,
    pub description: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArFinding {
    pub uuid: String,
    pub title: String,
    pub target: FindingTarget,
    #[serde(rename = "related-observations", skip_serializing_if = "Vec::is_empty")]
    pub related_observations: Vec<RelatedObservation>,
}

#[derive(Debug, Clone, Serialize)]
pub struct FindingTarget {
    #[serde(rename = "type")]
    pub target_type: String,
    #[serde(rename = "target-id")]
    pub target_id: String,
    pub status: TargetStatus,
}

#[derive(Debug, Clone, Serialize)]
pub struct TargetStatus {
    pub state: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct RelatedObservation {
    #[serde(rename = "observation-uuid")]
    pub observation_uuid: String,
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::models::finding::Severity;
    use crate::models::scan::ScanType;

    fn finding(fp: &str, cwe: Option<&str>, refs: &[&str]) -> Finding {
        let mut f = Finding::new(
            "repo".into(),
            fp.into(),
            "semgrep".into(),
            ScanType::Sast,
            "hardcoded credential".into(),
            "desc".into(),
            Severity::High,
        );
        f.cwe = cwe.map(Into::into);
        f.file_path = Some("src/auth.rs".into());
        f.line_number = Some(42);
        f.control_refs = refs.iter().map(|s| s.to_string()).collect();
        f
    }

    fn at() -> DateTime<Utc> {
        DateTime::parse_from_rfc3339("2026-07-20T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc)
    }

    #[test]
    fn mapped_finding_becomes_control_finding() {
        let doc = assess(&[finding("f1", Some("CWE-798"), &["cra-ai-8"])], at());
        let r = &doc.assessment_results.results[0];
        assert_eq!(r.observations.len(), 1);
        assert_eq!(r.findings.len(), 1);
        assert_eq!(r.findings[0].target.target_id, "cra-ai-8_smt");
        assert_eq!(r.findings[0].target.status.state, "not-satisfied");
        assert_eq!(
            r.reviewed_controls.control_selections[0]
                .include_controls
                .len(),
            1
        );
    }

    #[test]
    fn unmapped_finding_is_reported_as_is() {
        let doc = assess(&[finding("f1", Some("CWE-319"), &[])], at());
        let r = &doc.assessment_results.results[0];
        assert_eq!(r.observations.len(), 1); // still emitted...
        assert!(r.findings.is_empty()); // ...but no control finding
        assert!(r.reviewed_controls.control_selections[0]
            .include_controls
            .is_empty());
        let props: Vec<(&str, &str)> = r.observations[0]
            .props
            .iter()
            .map(|p| (p.name.as_str(), p.value.as_str()))
            .collect();
        assert!(props.contains(&("mapping", "unmapped")));
        assert!(props.contains(&("cwe", "CWE-319")));
    }

    #[test]
    fn false_positive_is_excluded() {
        let mut f = finding("f1", Some("CWE-798"), &["cra-ai-8"]);
        f.status = FindingStatus::FalsePositive;
        let doc = assess(&[f], at());
        assert!(doc.assessment_results.results[0].observations.is_empty());
    }

    #[test]
    fn deterministic_and_valid_oscal() {
        let mk = || {
            vec![
                finding("f1", Some("CWE-798"), &["cra-ai-8"]),
                finding("f2", Some("CWE-319"), &[]),
            ]
        };
        let a = serde_json::to_string(&assess(&mk(), at())).unwrap();
        let b = serde_json::to_string(&assess(&mk(), at())).unwrap();
        assert_eq!(a, b);
        assert!(a.contains("\"oscal-version\":\"1.1.2\""));
        assert!(a.contains("\"not-satisfied\""));
        assert!(a.contains("\"mapping\""));
    }
}
