"""Tests for health checks."""

from datetime import date, timedelta
from pathlib import Path

import pytest

from supermemory.init import init_project
from supermemory.health import check_health, format_health


@pytest.fixture
def healthy_memory(tmp_path):
    """Create a healthy .memory directory."""
    root = init_project(project="test", me="alice", base=tmp_path)

    # Add a fresh system doc
    today = date.today().isoformat()
    (root / "systems" / "api.md").write_text(
        f"---\nowner: alice\nlast_verified: {today}\npaths: []\ntags: []\n---\n# API\n"
    )

    return root


@pytest.fixture
def stale_memory(tmp_path):
    """Create .memory with stale docs."""
    root = init_project(project="test", me="bob", base=tmp_path)

    # Add a stale system doc
    old_date = (date.today() - timedelta(days=30)).isoformat()
    (root / "systems" / "old-system.md").write_text(
        f"---\nowner: bob\nlast_verified: {old_date}\npaths: []\ntags: []\n---\n# Old\n"
    )

    # Add a system doc with no last_verified
    (root / "systems" / "never-verified.md").write_text(
        "---\nowner:\nlast_verified:\npaths: []\ntags: []\n---\n# Never Verified\n"
    )

    return root


def test_healthy_memory(healthy_memory):
    issues = check_health(healthy_memory)

    # Healthy memory might still have "no sessions" warning for alice
    stale_issues = [i for i in issues if i["category"] == "stale"]
    assert len(stale_issues) == 0


def test_stale_system_detected(stale_memory):
    issues = check_health(stale_memory)

    stale = [i for i in issues if i["category"] == "stale"]
    assert len(stale) == 2  # old-system + never-verified

    messages = [i["message"] for i in stale]
    assert any("old-system" in m for m in messages)
    assert any("never-verified" in m for m in messages)


def test_missing_template_detected(tmp_path):
    root = init_project(project="test", base=tmp_path)

    # Remove a template
    (root / "systems" / "_template.md").unlink()

    issues = check_health(root)
    missing = [i for i in issues if i["category"] == "missing_template"]
    assert len(missing) == 1
    assert "systems" in missing[0]["message"]


def test_orphaned_scratch_detected(tmp_path):
    root = init_project(project="test", base=tmp_path)

    # Add scratch files
    (root / "scratch" / "notes.md").write_text("# Some scratch notes")
    (root / "scratch" / "ideas.md").write_text("# Some ideas")

    issues = check_health(root)
    orphaned = [i for i in issues if i["category"] == "orphaned_scratch"]
    assert len(orphaned) == 1
    assert "2 file(s)" in orphaned[0]["message"]


def test_no_sessions_warning(tmp_path):
    root = init_project(project="test", me="carol", base=tmp_path)

    issues = check_health(root)
    no_sess = [i for i in issues if i["category"] == "no_sessions"]
    assert len(no_sess) == 1
    assert "carol" in no_sess[0]["message"]


def test_format_health_no_issues():
    assert "healthy" in format_health([])


def test_format_health_with_issues():
    issues = [
        {"level": "warning", "category": "stale", "message": "test stale"},
        {"level": "error", "category": "missing_template", "message": "test missing"},
    ]
    output = format_health(issues)
    assert "2 issue(s)" in output
    assert "test stale" in output
    assert "test missing" in output
