//! File-system layer — discovers, reads, and writes `.mps` files.
//!
//! The CLI delegates all I/O to [`Store`]; no direct file operations happen
//! in command handlers.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use chrono::NaiveDate;
use indexmap::IndexMap;
use crate::constants::{mps_file_name_regexp, new_file_name, MPS_EXT};
use crate::elements::Element;
use crate::error::MpsError;
use crate::parser;
use crate::ref_resolver::RefResolver;

#[allow(dead_code)]
pub struct SearchResult {
    pub element:  Element,
    pub file:     PathBuf,
    pub date_str: String,  // "YYYYMMDD"
}

pub struct Store {
    storage_dir: PathBuf,
}

impl Store {
    pub fn new(storage_dir: impl Into<PathBuf>) -> Self {
        Store { storage_dir: storage_dir.into() }
    }

    /// First .mps file matching date, or None.
    pub fn find_file(&self, date: NaiveDate) -> Option<PathBuf> {
        self.find_files(date).into_iter().next()
    }

    /// All .mps files matching date (handles multiple files per day).
    pub fn find_files(&self, date: NaiveDate) -> Vec<PathBuf> {
        let prefix = date.format("%Y%m%d").to_string();
        let re = mps_file_name_regexp();
        let mut files: Vec<PathBuf> = std::fs::read_dir(&self.storage_dir)
            .map(|rd| {
                rd.filter_map(|e| e.ok())
                    .map(|e| e.path())
                    .filter(|p| {
                        p.extension().and_then(|e| e.to_str()) == Some(MPS_EXT)
                            && p.file_name()
                                .and_then(|n| n.to_str())
                                .map(|n| re.is_match(n) && n.starts_with(&prefix))
                                .unwrap_or(false)
                    })
                    .collect()
            })
            .unwrap_or_default();
        files.sort();
        files
    }

    /// Existing file for date, or a generated new path (file not yet created).
    pub fn find_or_create_path(&self, date: NaiveDate) -> PathBuf {
        self.find_file(date)
            .unwrap_or_else(|| self.storage_dir.join(new_file_name(date)))
    }

    /// Parsed elements for date. Returns empty map if no file exists.
    pub fn parse_date(&self, date: NaiveDate) -> Result<IndexMap<String, Element>, MpsError> {
        match self.find_file(date) {
            None    => Ok(IndexMap::new()),
            Some(p) => parser::parse_file(&p),
        }
    }

    /// Append a new element to date's file (creates file if absent).
    pub fn append(
        &self,
        kind:  &str,
        body:  &str,
        tags:  &[String],
        attrs: &[(&str, &str)],
        date:  NaiveDate,
    ) -> Result<PathBuf, MpsError> {
        let mut parts: Vec<String> = attrs.iter().map(|(k, v)| format!("{}: {}", k, v)).collect();
        parts.extend(tags.iter().cloned());
        let args_str = parts.join(", ");

        let path = self.find_or_create_path(date);
        let chunk = format!("\n@{}[{}]{{\n  {}\n}}\n", kind, args_str, body);
        use std::io::Write;
        let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
        f.write_all(chunk.as_bytes())?;
        Ok(path)
    }

    /// All .mps files in storage_dir, sorted by filename (chronological).
    pub fn all_files(&self) -> Result<Vec<PathBuf>, MpsError> {
        let re = mps_file_name_regexp();
        let mut files: Vec<PathBuf> = std::fs::read_dir(&self.storage_dir)?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| {
                p.extension().and_then(|e| e.to_str()) == Some(MPS_EXT)
                    && p.file_name()
                        .and_then(|n| n.to_str())
                        .map(|n| re.is_match(n))
                        .unwrap_or(false)
            })
            .collect();
        files.sort();
        Ok(files)
    }

    /// Files whose date-stamp >= since_date.
    pub fn files_since(&self, since_date: NaiveDate) -> Result<Vec<PathBuf>, MpsError> {
        let since_str = since_date.format("%Y%m%d").to_string();
        let files = self.all_files()?
            .into_iter()
            .filter(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .map(|n| &n[..8] >= since_str.as_str())
                    .unwrap_or(false)
            })
            .collect();
        Ok(files)
    }

    /// Unique sorted dates for which .mps files exist.
    pub fn all_file_dates(&self) -> Result<Vec<NaiveDate>, MpsError> {
        let mut seen = std::collections::HashSet::new();
        let mut dates: Vec<NaiveDate> = self.all_files()?
            .iter()
            .filter_map(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .and_then(|n| NaiveDate::parse_from_str(&n[..8], "%Y%m%d").ok())
            })
            .filter(|d| seen.insert(*d))
            .collect();
        dates.sort();
        Ok(dates)
    }

    /// Rewrite an element's typed attributes in-place, atomically.
    ///
    /// `ref_str` may be an epoch ref (e.g. "20260428.1") or a human ref (e.g. "task-1").
    /// Human refs are resolved against `date` (defaults to today in the caller).
    /// `new_attrs` maps attribute name → new value (e.g. {"status" → "done"}).
    ///
    /// Returns `true` on success, `false` if ref not found or file unchanged.
    pub fn rewrite_element(
        &self,
        ref_str:   &str,
        new_attrs: &HashMap<String, String>,
        date:      NaiveDate,
    ) -> Result<bool, MpsError> {
        let (epoch_ref, path) = self.resolve_ref_to_path(ref_str, date)?;
        let (epoch_ref, path) = match (epoch_ref, path) {
            (Some(e), Some(p)) => (e, p),
            _ => return Ok(false),
        };

        let elements = parser::parse_file(&path)?;
        let el = match elements.get(&epoch_ref) {
            Some(e) => e.clone(),
            None    => return Ok(false),
        };
        if el.is_unknown() { return Ok(false); }

        self.rewrite_element_in_file(&path, &el, &epoch_ref, &elements, new_attrs)
    }

    // ── private helpers ──────────────────────────────────────────────────────

    /// Resolve a ref string to (epoch_ref, file_path).
    /// Epoch refs (YYYYMMDD.n...) encode their own date; human refs need the given date.
    fn resolve_ref_to_path(
        &self,
        ref_str: &str,
        date:    NaiveDate,
    ) -> Result<(Option<String>, Option<PathBuf>), MpsError> {
        // Epoch ref: 8 ASCII digits followed by '.' then a digit
        let is_epoch = ref_str.len() >= 10
            && ref_str[..8].chars().all(|c| c.is_ascii_digit())
            && ref_str.chars().nth(8) == Some('.')
            && ref_str.chars().nth(9).map(|c| c.is_ascii_digit()).unwrap_or(false);

        if is_epoch {
            let d = NaiveDate::parse_from_str(&ref_str[..8], "%Y%m%d")
                .map_err(|_| MpsError::DateParseError(ref_str[..8].to_string()))?;
            let path = self.find_file(d);
            Ok((Some(ref_str.to_string()), path))
        } else {
            let path = match self.find_file(date) {
                Some(p) => p,
                None    => return Ok((None, None)),
            };
            let elements   = parser::parse_file(&path)?;
            let resolver   = RefResolver::new(&elements);
            let epoch_ref  = resolver.to_epoch(ref_str).map(|s| s.to_string());
            Ok((epoch_ref, Some(path)))
        }
    }

    /// Rewrite the `@type[args]{` opening line in-place and save atomically.
    ///
    /// `epoch_ref` and `all_elements` are used to determine WHICH occurrence of the
    /// opening pattern to replace when multiple elements share identical raw_args.
    /// Elements are sorted by their numeric ref-path parts (same order as RefResolver),
    /// which mirrors the order openers appear in the file. This makes the N-th
    /// occurrence of the pattern map to the correct element even with duplicate args.
    fn rewrite_element_in_file(
        &self,
        path:         &Path,
        el:           &Element,
        epoch_ref:    &str,
        all_elements: &IndexMap<String, Element>,
        new_attrs:    &HashMap<String, String>,
    ) -> Result<bool, MpsError> {
        let content   = std::fs::read_to_string(path)?;
        let type_name = el.sign();
        let raw       = el.raw_args();

        // Merge new attrs over existing typed attrs (preserve order; append new keys at end).
        let mut merged: Vec<(String, String)> = el.typed_attrs();
        for (k, v) in new_attrs {
            if let Some(pos) = merged.iter().position(|(ek, _)| ek == k) {
                merged[pos].1 = v.clone();
            } else {
                merged.push((k.clone(), v.clone()));
            }
        }

        // Build new args string: named attrs first, then tags.
        let attr_parts: Vec<String> = merged.iter()
            .filter(|(_, v)| !v.is_empty())
            .map(|(k, v)| format!("{}: {}", k, v))
            .collect();
        let new_args_str: String = attr_parts.into_iter()
            .chain(el.tags().iter().cloned())
            .collect::<Vec<_>>()
            .join(", ");

        // Build a regex matching the current element opening line.
        let esc_type = regex::escape(type_name);
        let old_pat = if raw.is_empty() {
            format!(r"@{}(?:\[\])?\s*\{{", esc_type)
        } else {
            format!(r"@{}\[{}\]\s*\{{", esc_type, regex::escape(raw))
        };

        let re = regex::Regex::new(&old_pat)
            .map_err(|e| MpsError::ParseError { file: path.display().to_string(), msg: e.to_string() })?;

        // Determine which occurrence to replace.
        // Sort all elements by their numeric ref-path parts — this order mirrors the
        // order in which openers appear in the file (depth-first, opening order).
        // Count how many elements with the same (sign, raw_args) appear before our
        // target in that sorted order; skip synthetic root (keys without any dot).
        let mut sorted_keys: Vec<&String> = all_elements.keys().collect();
        sorted_keys.sort_by(|a, b| {
            let ap: Vec<u64> = a.split('.').filter_map(|s| s.parse().ok()).collect();
            let bp: Vec<u64> = b.split('.').filter_map(|s| s.parse().ok()).collect();
            ap.cmp(&bp)
        });

        let mut occurrence: usize = 0;
        for key in &sorted_keys {
            if *key == epoch_ref { break; }
            // Skip synthetic root (no dot → single-segment key like "20260302")
            if !key.contains('.') { continue; }
            if let Some(other) = all_elements.get(*key) {
                if other.sign() == type_name && other.raw_args() == raw {
                    occurrence += 1;
                }
            }
        }

        // Replace specifically the (occurrence)-th match (0-indexed).
        let new_open = format!("@{}[{}]{{", type_name, new_args_str);
        let mut match_n = 0usize;
        let mut new_content: Option<String> = None;
        for m in re.find_iter(&content) {
            if match_n == occurrence {
                new_content = Some(format!("{}{}{}", &content[..m.start()], new_open, &content[m.end()..]));
                break;
            }
            match_n += 1;
        }

        let new_content = match new_content {
            Some(c) => c,
            None    => return Ok(false),
        };
        if new_content == content { return Ok(false); }

        // Atomic write: tmp file → rename
        let tmp_path = PathBuf::from(format!("{}.tmp.{}", path.display(), std::process::id()));
        std::fs::write(&tmp_path, &new_content)?;
        std::fs::rename(&tmp_path, path)?;
        Ok(true)
    }

    /// Full-text search across files. Returns matched elements with file and date_str.
    pub fn search(
        &self,
        query:       &str,
        type_filter: Option<&str>,
        tag_filter:  Option<&str>,
        since_date:  Option<NaiveDate>,
    ) -> Result<Vec<SearchResult>, MpsError> {
        let files = match since_date {
            Some(d) => self.files_since(d)?,
            None    => self.all_files()?,
        };

        let query_lower = query.to_lowercase();
        let mut results = Vec::new();

        for file in files {
            let date_str = file.file_name()
                .and_then(|n| n.to_str())
                .map(|n| n[..8].to_string())
                .unwrap_or_default();

            let elements = parser::parse_file(&file)?;

            for (_, el) in elements {
                if el.is_mps_group() || el.is_unknown() { continue; }

                if let Some(tf) = type_filter {
                    if el.sign() != tf { continue; }
                }
                if let Some(tag) = tag_filter {
                    if !el.tags().iter().any(|t| t == tag) { continue; }
                }
                if !el.body_str().to_lowercase().contains(&query_lower) { continue; }

                results.push(SearchResult {
                    element: el,
                    file: file.clone(),
                    date_str: date_str.clone(),
                });
            }
        }

        Ok(results)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::elements::ElementKind;

    fn make_store(dir: &Path) -> Store {
        Store::new(dir)
    }

    fn write_file(dir: &Path, name: &str, content: &str) -> PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn test_find_file_absent() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        assert!(store.find_file(date).is_none());
    }

    #[test]
    fn test_find_file_present() {
        let dir = tempfile::tempdir().unwrap();
        write_file(dir.path(), "20260101.1700000000.mps", "@task{ Hi }");
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        assert!(store.find_file(date).is_some());
    }

    #[test]
    fn test_parse_date_empty() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
        let els = store.parse_date(date).unwrap();
        assert!(els.is_empty());
    }

    #[test]
    fn test_append_creates_file() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 4, 28).unwrap();
        let path = store.append("task", "Do a thing", &["work".into()], &[], date).unwrap();
        assert!(path.exists());

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("@task"));
        assert!(content.contains("Do a thing"));
    }

    #[test]
    fn test_append_then_parse() {
        let dir = tempfile::tempdir().unwrap();
        let store = make_store(dir.path());
        let date = NaiveDate::from_ymd_opt(2026, 4, 28).unwrap();
        store.append("task", "Test task", &["work".into()], &[], date).unwrap();
        let els = store.parse_date(date).unwrap();
        // root mps + task
        assert!(els.len() >= 2);
        let has_task = els.values().any(|e| e.kind() == ElementKind::Task);
        assert!(has_task);
    }

    #[test]
    fn test_search_by_query() {
        let dir = tempfile::tempdir().unwrap();
        write_file(dir.path(), "20260101.1700000000.mps", "@task{ auth token fix }");
        let store = make_store(dir.path());
        let results = store.search("auth", None, None, None).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].date_str, "20260101");
    }

    #[test]
    fn test_files_since() {
        let dir = tempfile::tempdir().unwrap();
        write_file(dir.path(), "20260101.1700000000.mps", "@note{ old }");
        write_file(dir.path(), "20260601.1800000000.mps", "@note{ new }");
        let store = make_store(dir.path());
        let since = NaiveDate::from_ymd_opt(2026, 3, 1).unwrap();
        let files = store.files_since(since).unwrap();
        assert_eq!(files.len(), 1);
        assert!(files[0].to_str().unwrap().contains("20260601"));
    }
}
