use crate::pwc::CodeLink;
use crate::repos::Repository;
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RepositoryAnalysis {
    pub has_license: bool,
    pub is_stale: bool,
    pub is_archived: bool,
    pub primary_language: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct GapAssessment {
    pub implementation_gap_score: u32,
    pub components: ScoreComponents,
    pub gaps: Vec<Gap>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScoreComponents {
    pub no_code_score: u32,
    pub prototype_only_score: u32,
    pub stale_repo_score: u32,
    pub packaging_gap_score: u32,
    pub docs_gap_score: u32,
    pub tests_gap_score: u32,
    pub license_gap_score: u32,
    pub reproducibility_gap_score: u32,
    pub ecosystem_gap_score: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Gap {
    pub gap_type: GapType,
    pub points: u32,
    pub explanation: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum GapType {
    NoPublicImplementationFound,
    NoKnownPapersWithCodeEntry,
    StaleRepository,
    ArchivedRepository,
    UnclearOrRestrictiveLicense,
}

pub fn analyze_repository(repo: &Repository) -> RepositoryAnalysis {
    RepositoryAnalysis {
        has_license: repo
            .license
            .as_deref()
            .is_some_and(|license| !license.trim().is_empty() && license != "NOASSERTION"),
        is_stale: repo.last_commit_date.as_deref().is_some_and(is_stale_date),
        is_archived: repo.archived.unwrap_or(false),
        primary_language: repo.primary_language.clone(),
    }
}

pub fn assess(code_links: &[CodeLink], repositories: &[Repository]) -> GapAssessment {
    let repositories = dedup_repositories(repositories.to_vec());
    let analyses: Vec<_> = repositories.iter().map(analyze_repository).collect();
    let mut components = ScoreComponents::default();
    let mut gaps = Vec::new();

    if code_links.is_empty() {
        components.no_code_score += 10;
        gaps.push(Gap {
            gap_type: GapType::NoKnownPapersWithCodeEntry,
            points: 10,
            explanation: "Papers with Code returned no known code links.".into(),
        });
    }
    if code_links.is_empty() && repositories.is_empty() {
        components.no_code_score += 40;
        gaps.push(Gap {
            gap_type: GapType::NoPublicImplementationFound,
            points: 40,
            explanation:
                "No public implementation was found from Papers with Code or repository search."
                    .into(),
        });
    }
    if analyses.iter().any(|a| a.is_archived) {
        components.stale_repo_score += 15;
        gaps.push(Gap {
            gap_type: GapType::ArchivedRepository,
            points: 15,
            explanation: "At least one discovered repository is archived.".into(),
        });
    }
    if !analyses.is_empty() && analyses.iter().all(|a| a.is_stale) {
        components.stale_repo_score += 15;
        gaps.push(Gap {
            gap_type: GapType::StaleRepository,
            points: 15,
            explanation: "All discovered repositories with commit dates look stale.".into(),
        });
    }
    if !analyses.is_empty() && analyses.iter().all(|a| !a.has_license) {
        components.license_gap_score += 10;
        gaps.push(Gap {
            gap_type: GapType::UnclearOrRestrictiveLicense,
            points: 10,
            explanation: "No discovered repository has a clear license signal.".into(),
        });
    }

    let implementation_gap_score = components.no_code_score
        + components.prototype_only_score
        + components.stale_repo_score
        + components.packaging_gap_score
        + components.docs_gap_score
        + components.tests_gap_score
        + components.license_gap_score
        + components.reproducibility_gap_score
        + components.ecosystem_gap_score;

    GapAssessment {
        implementation_gap_score,
        components,
        gaps,
    }
}

pub fn dedup_repositories(repositories: Vec<Repository>) -> Vec<Repository> {
    let mut out = Vec::new();
    for repo in repositories {
        let key = normalized_url(&repo.url);
        if !out
            .iter()
            .any(|existing: &Repository| normalized_url(&existing.url) == key)
        {
            out.push(repo);
        }
    }
    out
}

fn normalized_url(url: &str) -> String {
    url.trim_end_matches('/')
        .trim_end_matches(".git")
        .to_ascii_lowercase()
}

fn is_stale_date(date: &str) -> bool {
    DateTime::parse_from_rfc3339(date)
        .map(|date| {
            Utc::now().signed_duration_since(date.with_timezone(&Utc)) > Duration::days(365)
        })
        .unwrap_or(false)
}
