//! Vulnerability data structures.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Reference to a vulnerability affecting a component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VulnerabilityRef {
    /// Vulnerability identifier (CVE, GHSA, etc.)
    pub id: String,
    /// Source database
    pub source: VulnerabilitySource,
    /// Severity level
    pub severity: Option<Severity>,
    /// CVSS scores
    pub cvss: Vec<CvssScore>,
    /// Affected version ranges
    pub affected_versions: Vec<String>,
    /// Remediation information
    pub remediation: Option<Remediation>,
    /// Description
    pub description: Option<String>,
    /// CWE identifiers
    pub cwes: Vec<String>,
    /// Published date
    pub published: Option<DateTime<Utc>>,
    /// Last modified date
    pub modified: Option<DateTime<Utc>>,
    /// Whether this CVE is in CISA's Known Exploited Vulnerabilities catalog
    pub is_kev: bool,
    /// KEV-specific metadata if applicable
    pub kev_info: Option<KevInfo>,
}

/// CISA Known Exploited Vulnerabilities (KEV) catalog information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KevInfo {
    /// Date added to KEV catalog
    pub date_added: DateTime<Utc>,
    /// Due date for remediation (per CISA directive)
    pub due_date: DateTime<Utc>,
    /// Whether known to be used in ransomware campaigns
    pub known_ransomware_use: bool,
    /// Required action description
    pub required_action: String,
    /// Vendor/project name
    pub vendor_project: Option<String>,
    /// Product name
    pub product: Option<String>,
}

impl KevInfo {
    /// Create new KEV info
    pub fn new(date_added: DateTime<Utc>, due_date: DateTime<Utc>, required_action: String) -> Self {
        Self {
            date_added,
            due_date,
            known_ransomware_use: false,
            required_action,
            vendor_project: None,
            product: None,
        }
    }

    /// Check if remediation is overdue
    pub fn is_overdue(&self) -> bool {
        Utc::now() > self.due_date
    }

    /// Days until due date (negative if overdue)
    pub fn days_until_due(&self) -> i64 {
        (self.due_date - Utc::now()).num_days()
    }
}

impl VulnerabilityRef {
    /// Create a new vulnerability reference
    pub fn new(id: String, source: VulnerabilitySource) -> Self {
        Self {
            id,
            source,
            severity: None,
            cvss: Vec::new(),
            affected_versions: Vec::new(),
            remediation: None,
            description: None,
            cwes: Vec::new(),
            published: None,
            modified: None,
            is_kev: false,
            kev_info: None,
        }
    }

    /// Check if this vulnerability is actively exploited (KEV)
    pub fn is_actively_exploited(&self) -> bool {
        self.is_kev
    }

    /// Check if this is a ransomware-related KEV entry
    pub fn is_ransomware_related(&self) -> bool {
        self.kev_info
            .as_ref()
            .map(|k| k.known_ransomware_use)
            .unwrap_or(false)
    }

    /// Get the highest CVSS score
    pub fn max_cvss_score(&self) -> Option<f32> {
        self.cvss
            .iter()
            .map(|c| c.base_score)
            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
    }
}

impl PartialEq for VulnerabilityRef {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id && self.source == other.source
    }
}

impl Eq for VulnerabilityRef {}

impl std::hash::Hash for VulnerabilityRef {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id.hash(state);
        self.source.hash(state);
    }
}

/// Vulnerability database source
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VulnerabilitySource {
    Nvd,
    Ghsa,
    Osv,
    Snyk,
    Sonatype,
    VulnDb,
    Cve,
    Other(String),
}

impl fmt::Display for VulnerabilitySource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VulnerabilitySource::Nvd => write!(f, "NVD"),
            VulnerabilitySource::Ghsa => write!(f, "GHSA"),
            VulnerabilitySource::Osv => write!(f, "OSV"),
            VulnerabilitySource::Snyk => write!(f, "Snyk"),
            VulnerabilitySource::Sonatype => write!(f, "Sonatype"),
            VulnerabilitySource::VulnDb => write!(f, "VulnDB"),
            VulnerabilitySource::Cve => write!(f, "CVE"),
            VulnerabilitySource::Other(s) => write!(f, "{}", s),
        }
    }
}

/// Severity level
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Severity {
    Critical,
    High,
    Medium,
    Low,
    Info,
    None,
    #[default]
    Unknown,
}

impl Severity {
    /// Create severity from CVSS score
    pub fn from_cvss(score: f32) -> Self {
        match score {
            s if s >= 9.0 => Severity::Critical,
            s if s >= 7.0 => Severity::High,
            s if s >= 4.0 => Severity::Medium,
            s if s >= 0.1 => Severity::Low,
            0.0 => Severity::None,
            _ => Severity::Unknown,
        }
    }

    /// Get numeric priority (lower is more severe)
    pub fn priority(&self) -> u8 {
        match self {
            Severity::Critical => 0,
            Severity::High => 1,
            Severity::Medium => 2,
            Severity::Low => 3,
            Severity::Info => 4,
            Severity::None => 5,
            Severity::Unknown => 6,
        }
    }
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Severity::Critical => write!(f, "Critical"),
            Severity::High => write!(f, "High"),
            Severity::Medium => write!(f, "Medium"),
            Severity::Low => write!(f, "Low"),
            Severity::Info => write!(f, "Info"),
            Severity::None => write!(f, "None"),
            Severity::Unknown => write!(f, "Unknown"),
        }
    }
}


/// CVSS score information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CvssScore {
    /// CVSS version
    pub version: CvssVersion,
    /// Base score (0.0 - 10.0)
    pub base_score: f32,
    /// Attack vector
    pub vector: Option<String>,
    /// Exploitability score
    pub exploitability_score: Option<f32>,
    /// Impact score
    pub impact_score: Option<f32>,
}

impl CvssScore {
    /// Create a new CVSS score
    pub fn new(version: CvssVersion, base_score: f32) -> Self {
        Self {
            version,
            base_score,
            vector: None,
            exploitability_score: None,
            impact_score: None,
        }
    }
}

/// CVSS version
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CvssVersion {
    V2,
    V3,
    V31,
    V4,
}

impl fmt::Display for CvssVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CvssVersion::V2 => write!(f, "2.0"),
            CvssVersion::V3 => write!(f, "3.0"),
            CvssVersion::V31 => write!(f, "3.1"),
            CvssVersion::V4 => write!(f, "4.0"),
        }
    }
}

/// Remediation information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Remediation {
    /// Remediation type
    pub remediation_type: RemediationType,
    /// Description
    pub description: Option<String>,
    /// Fixed version
    pub fixed_version: Option<String>,
}

/// Remediation type
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RemediationType {
    Patch,
    Upgrade,
    Workaround,
    Mitigation,
    None,
}

impl fmt::Display for RemediationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RemediationType::Patch => write!(f, "Patch"),
            RemediationType::Upgrade => write!(f, "Upgrade"),
            RemediationType::Workaround => write!(f, "Workaround"),
            RemediationType::Mitigation => write!(f, "Mitigation"),
            RemediationType::None => write!(f, "None"),
        }
    }
}

/// VEX (Vulnerability Exploitability eXchange) status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VexStatus {
    /// VEX state
    pub status: VexState,
    /// Justification for the status
    pub justification: Option<VexJustification>,
    /// Action statement
    pub action_statement: Option<String>,
    /// Impact statement
    pub impact_statement: Option<String>,
    /// Response type
    pub response: Option<VexResponse>,
    /// Details
    pub detail: Option<String>,
}

impl VexStatus {
    /// Create a new VEX status
    pub fn new(status: VexState) -> Self {
        Self {
            status,
            justification: None,
            action_statement: None,
            impact_statement: None,
            response: None,
            detail: None,
        }
    }
}

/// VEX state
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VexState {
    Affected,
    NotAffected,
    Fixed,
    UnderInvestigation,
}

impl fmt::Display for VexState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VexState::Affected => write!(f, "Affected"),
            VexState::NotAffected => write!(f, "Not Affected"),
            VexState::Fixed => write!(f, "Fixed"),
            VexState::UnderInvestigation => write!(f, "Under Investigation"),
        }
    }
}

/// VEX justification for not_affected status
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VexJustification {
    ComponentNotPresent,
    VulnerableCodeNotPresent,
    VulnerableCodeNotInExecutePath,
    VulnerableCodeCannotBeControlledByAdversary,
    InlineMitigationsAlreadyExist,
}

impl fmt::Display for VexJustification {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VexJustification::ComponentNotPresent => write!(f, "Component not present"),
            VexJustification::VulnerableCodeNotPresent => write!(f, "Vulnerable code not present"),
            VexJustification::VulnerableCodeNotInExecutePath => {
                write!(f, "Vulnerable code not in execute path")
            }
            VexJustification::VulnerableCodeCannotBeControlledByAdversary => {
                write!(f, "Vulnerable code cannot be controlled by adversary")
            }
            VexJustification::InlineMitigationsAlreadyExist => {
                write!(f, "Inline mitigations already exist")
            }
        }
    }
}

/// VEX response type
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VexResponse {
    CanNotFix,
    WillNotFix,
    Update,
    Rollback,
    Workaround,
}

impl fmt::Display for VexResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VexResponse::CanNotFix => write!(f, "Can Not Fix"),
            VexResponse::WillNotFix => write!(f, "Will Not Fix"),
            VexResponse::Update => write!(f, "Update"),
            VexResponse::Rollback => write!(f, "Rollback"),
            VexResponse::Workaround => write!(f, "Workaround"),
        }
    }
}
