//! `.hephaes/manifest.json` — the provenance manifest (plan §7).
//!
//! Maps every source file to its content hash and the wiki pages it feeds (a
//! reverse index), plus the last reconciled commit. `update` uses content
//! hashes to detect change (works for non-git repos) and the reverse index to
//! find which pages a changed file affects.

use crate::repo::Scan;
use crate::wiki::index;
use anyhow::{Context, Result};
use globset::Glob;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SourceEntry {
    pub hash: String,
    /// Wiki page paths (relative to the wiki dir) derived from this source.
    #[serde(default)]
    pub pages: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Manifest {
    pub last_commit: Option<String>,
    pub updated: Option<String>,
    /// keyed by source path relative to repo root.
    #[serde(default)]
    pub sources: BTreeMap<String, SourceEntry>,
}

#[derive(Debug, Default)]
pub struct ChangeSet {
    pub added: Vec<String>,
    pub modified: Vec<String>,
    pub deleted: Vec<String>,
}

impl ChangeSet {
    pub fn is_empty(&self) -> bool {
        self.added.is_empty() && self.modified.is_empty() && self.deleted.is_empty()
    }
}

impl Manifest {
    pub fn load(path: &Path) -> Manifest {
        std::fs::read_to_string(path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default()
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let json = serde_json::to_string_pretty(self).context("serializing manifest")?;
        std::fs::write(path, json).with_context(|| format!("writing {}", path.display()))
    }

    /// Compare the current scan against stored hashes.
    pub fn diff_against(&self, scan: &Scan) -> ChangeSet {
        let mut cs = ChangeSet::default();
        let mut seen = std::collections::BTreeSet::new();
        for f in &scan.files {
            seen.insert(f.rel.clone());
            let hash = hash_file(&f.abs);
            match self.sources.get(&f.rel) {
                None => cs.added.push(f.rel.clone()),
                Some(prev) if prev.hash != hash => cs.modified.push(f.rel.clone()),
                Some(_) => {}
            }
        }
        for key in self.sources.keys() {
            if !seen.contains(key) {
                cs.deleted.push(key.clone());
            }
        }
        cs
    }

    /// Wiki pages affected by a set of changed source paths (via reverse index).
    pub fn affected_pages(&self, changed: &[String]) -> Vec<String> {
        let mut pages = std::collections::BTreeSet::new();
        for c in changed {
            if let Some(entry) = self.sources.get(c) {
                for p in &entry.pages {
                    pages.insert(p.clone());
                }
            }
        }
        pages.into_iter().collect()
    }

    /// Recompute the manifest from the current scan and the wiki's pages: hash
    /// every source, and map source→pages using each page's `sources:` globs.
    pub fn rebuild(scan: &Scan, wiki_dir: &Path, last_commit: Option<String>) -> Manifest {
        let mut sources: BTreeMap<String, SourceEntry> = scan
            .files
            .iter()
            .map(|f| {
                (
                    f.rel.clone(),
                    SourceEntry {
                        hash: hash_file(&f.abs),
                        pages: Vec::new(),
                    },
                )
            })
            .collect();

        for page in index::list_pages(wiki_dir) {
            for pattern in &page.sources {
                let Ok(glob) = Glob::new(pattern) else {
                    continue;
                };
                let matcher = glob.compile_matcher();
                for (rel, entry) in sources.iter_mut() {
                    if matcher.is_match(rel) && !entry.pages.contains(&page.rel) {
                        entry.pages.push(page.rel.clone());
                    }
                }
            }
        }

        Manifest {
            last_commit,
            updated: Some(crate::util::today()),
            sources,
        }
    }
}

fn hash_file(path: &Path) -> String {
    match std::fs::read(path) {
        Ok(bytes) => {
            let hash = blake3::hash(&bytes);
            hash.to_hex().chars().take(16).collect()
        }
        Err(_) => String::new(),
    }
}
