from __future__ import annotations

from pathlib import Path

import pytest
from typer.testing import CliRunner

from eightmem.cli.main import app


runner = CliRunner()


USE_CASES = [
    {
        "name": "founder_journey_json",
        "path": "examples/use_cases/founder_journey.json",
        "expect": {
            "IDENTITY.md": "founder working on 8mem",
            "PREFERENCES.md": "keep answers concise and practical.",
            "CORRECTIONS.md": "use common language instead.",
            "EVOLUTION.md": "changed focus recently",
            "DECISIONS.md": "launch a local-first cli first",
        },
    },
    {
        "name": "consulting_transcript_txt",
        "path": "examples/use_cases/consulting_transcript.txt",
        "expect": {
            "IDENTITY.md": "engineering consultant for fintech teams",
            "PREFERENCES.md": "prefers numbered steps.",
            "CORRECTIONS.md": "do not use emojis",
            "EVOLUTION.md": "moved to weekly deliverables",
            "DECISIONS.md": "ship an audit checklist first",
        },
    },
    {
        "name": "enterprise_architect_nested_json",
        "path": "examples/use_cases/enterprise_architect_nested.json",
        "expect": {
            "IDENTITY.md": "principal architect leading cloud cost reduction",
            "PREFERENCES.md": "keep answers short and actionable.",
            "CORRECTIONS.md": "do not assume unlimited engineering bandwidth",
            "EVOLUTION.md": "changed from monthly reviews",
            "DECISIONS.md": "prioritize observability rollout first",
        },
    },
    {
        "name": "indie_hacker_multiturn_json",
        "path": "examples/use_cases/indie_hacker_multiturn.json",
        "expect": {
            "IDENTITY.md": "building a bootstrapped saas",
            "PREFERENCES.md": "prefers practical examples.",
            "CORRECTIONS.md": "avoid guessing customer personas",
            "EVOLUTION.md": "started with creator tools",
            "DECISIONS.md": "launch with csv import first",
        },
    },
    {
        "name": "support_ops_transcript_txt",
        "path": "examples/use_cases/support_ops_transcript.txt",
        "expect": {
            "IDENTITY.md": "support operations lead",
            "PREFERENCES.md": "keep answers concise and in checklist format.",
            "CORRECTIONS.md": "not every escalation needs engineering involvement",
            "EVOLUTION.md": "from now on we moved to shift handoff",
            "DECISIONS.md": "ship incident postmortem templates first",
        },
    },
]


@pytest.mark.parametrize("case", USE_CASES, ids=[c["name"] for c in USE_CASES])
def test_complex_use_cases_end_to_end(fake_home, tmp_path: Path, case: dict[str, object]):
    project_root = Path(__file__).resolve().parents[1]
    chat = project_root / str(case["path"])
    out_file = tmp_path / f"{case['name']}_context.md"

    init_res = runner.invoke(app, ["init"])
    assert init_res.exit_code == 0

    analyze_res = runner.invoke(app, ["analyze", str(chat)])
    assert analyze_res.exit_code == 0

    mirror_res = runner.invoke(app, ["mirror"])
    assert mirror_res.exit_code == 0
    assert "AI Believes About You" in mirror_res.stdout
    assert "Possible Contradictions:" in mirror_res.stdout

    export_res = runner.invoke(app, ["export-context", "-o", str(out_file)])
    assert export_res.exit_code == 0
    assert out_file.exists()

    mem = fake_home / "memory"
    for filename in (
        "IDENTITY.md",
        "BELIEFS.md",
        "PREFERENCES.md",
        "CORRECTIONS.md",
        "EVOLUTION.md",
        "DECISIONS.md",
    ):
        assert (mem / filename).exists(), f"Missing memory file: {filename}"

    expectations = case["expect"]
    assert isinstance(expectations, dict)
    for filename, expected_phrase in expectations.items():
        text = (mem / filename).read_text(encoding="utf-8").lower()
        assert "(empty)" not in text
        assert str(expected_phrase).lower() in text
