"""Health checks — staleness, orphans, missing templates."""

from __future__ import annotations

from datetime import date, timedelta
from pathlib import Path

from supermemory.config import load_config, memory_root
from supermemory.query import parse_frontmatter


def check_health(root: Path | None = None) -> list[dict]:
    """Run all health checks and return a list of issues.

    Each issue is a dict with 'level' (warning|error), 'category', and 'message'.
    """
    root = root or memory_root()
    config = load_config(root)
    issues: list[dict] = []

    issues.extend(_check_stale_systems(root, config))
    issues.extend(_check_missing_templates(root))
    issues.extend(_check_orphaned_scratch(root))
    issues.extend(_check_people_no_sessions(root))
    issues.extend(_check_systems_no_docs(root, config))

    return issues


def _check_stale_systems(root: Path, config: dict) -> list[dict]:
    """Find system docs past the staleness threshold."""
    issues = []
    stale_days = config.get("memory", {}).get("stale_after_days", 7)
    threshold = date.today() - timedelta(days=stale_days)

    systems_dir = root / "systems"
    if not systems_dir.is_dir():
        return issues

    for f in sorted(systems_dir.glob("*.md")):
        if f.name.startswith("_"):
            continue
        fm = parse_frontmatter(f)
        if fm is None:
            continue

        last_verified = fm.get("last_verified")
        if last_verified is None:
            issues.append({
                "level": "warning",
                "category": "stale",
                "message": f"systems/{f.name}: never verified (last_verified is empty)",
            })
        elif isinstance(last_verified, date) and last_verified < threshold:
            issues.append({
                "level": "warning",
                "category": "stale",
                "message": f"systems/{f.name}: last verified {last_verified} ({(date.today() - last_verified).days} days ago)",
            })

    return issues


def _check_missing_templates(root: Path) -> list[dict]:
    """Check that each memory subdirectory has a _template.md."""
    issues = []
    expected_dirs = ["systems", "decisions", "gotchas", "research", "people", "sessions"]

    for dirname in expected_dirs:
        d = root / dirname
        if d.is_dir() and not (d / "_template.md").exists():
            issues.append({
                "level": "error",
                "category": "missing_template",
                "message": f"{dirname}/_template.md is missing",
            })

    return issues


def _check_orphaned_scratch(root: Path) -> list[dict]:
    """Check for scratch files that might need promotion."""
    issues = []
    scratch_dir = root / "scratch"
    if not scratch_dir.is_dir():
        return issues

    scratch_files = [f for f in scratch_dir.glob("*.md") if not f.name.startswith("_")]
    if scratch_files:
        issues.append({
            "level": "warning",
            "category": "orphaned_scratch",
            "message": f"{len(scratch_files)} file(s) in scratch/ may need promotion: {', '.join(f.name for f in scratch_files)}",
        })

    return issues


def _check_people_no_sessions(root: Path) -> list[dict]:
    """Check for people with no recent session summaries."""
    issues = []
    people_dir = root / "people"
    sessions_dir = root / "sessions"

    if not people_dir.is_dir():
        return issues

    for f in sorted(people_dir.glob("*.md")):
        if f.name.startswith("_"):
            continue
        person_id = f.stem

        # Check if any session file mentions this person
        has_session = False
        if sessions_dir.is_dir():
            for sf in sessions_dir.glob("*.md"):
                if person_id in sf.name:
                    has_session = True
                    break

        if not has_session:
            issues.append({
                "level": "warning",
                "category": "no_sessions",
                "message": f"people/{f.name}: no session summaries found for {person_id}",
            })

    return issues


def _check_systems_no_docs(root: Path, config: dict) -> list[dict]:
    """Check if any discovered system paths lack documentation."""
    issues = []
    systems_dir = root / "systems"
    if not systems_dir.is_dir():
        return issues

    # Get existing system doc names
    existing = {f.stem for f in systems_dir.glob("*.md") if not f.name.startswith("_")}

    if not existing:
        issues.append({
            "level": "warning",
            "category": "no_system_docs",
            "message": "No system docs found. Run `atlasmemory systems discover` to auto-generate.",
        })

    return issues


def format_health(issues: list[dict]) -> str:
    """Format health check results for display."""
    if not issues:
        return "All checks passed. Memory is healthy."

    lines = [f"Found {len(issues)} issue(s):\n"]
    for issue in issues:
        icon = "!!" if issue["level"] == "error" else "  "
        lines.append(f"  {icon} [{issue['category']}] {issue['message']}")

    return "\n".join(lines)
