from __future__ import annotations

import json
from pathlib import Path

import pytest
from typer.testing import CliRunner

from eightmem.cli.main import app


runner = CliRunner()


CASES = [
    {
        "name": "pm_json",
        "suffix": ".json",
        "payload": [
            {
                "role": "user",
                "content": (
                    "I am a product manager for dev tools. "
                    "Please keep answers short and concrete. "
                    "We decided to ship onboarding docs first."
                ),
            }
        ],
        "expect": {
            "IDENTITY.md": "product manager for dev tools",
            "PREFERENCES.md": "keep answers short and concrete.",
            "DECISIONS.md": "ship onboarding docs first",
        },
    },
    {
        "name": "security_txt",
        "suffix": ".txt",
        "payload": (
            "user: I work as a security engineer.\n"
            "user: I prefer checklist format.\n"
            "user: Don't use emojis.\n"
            "user: Recently we moved to threat-model-first reviews.\n"
        ),
        "expect": {
            "IDENTITY.md": "security engineer",
            "PREFERENCES.md": "prefers checklist format.",
            "PREFERENCES.md#2": "avoid emojis.",
            "EVOLUTION.md": "recently we moved to threat-model-first reviews",
        },
    },
    {
        "name": "founder_txt",
        "suffix": ".txt",
        "payload": (
            "user: I'm building an AI scheduling startup.\n"
            "user: Keep answers concise and practical.\n"
            "user: Let's launch email integration first.\n"
        ),
        "expect": {
            "IDENTITY.md": "an ai scheduling startup",
            "PREFERENCES.md": "keep answers concise and practical.",
            "DECISIONS.md": "launch email integration first",
        },
    },
    {
        "name": "analyst_json",
        "suffix": ".json",
        "payload": [
            {
                "role": "user",
                "content": (
                    "My name is Riya. "
                    "I prefer numbered steps. "
                    "From now on we moved to weekly delivery."
                ),
            }
        ],
        "expect": {
            "IDENTITY.md": "riya",
            "PREFERENCES.md": "prefers numbered steps.",
            "EVOLUTION.md": "from now on we moved to weekly delivery",
        },
    },
    {
        "name": "research_txt",
        "suffix": ".txt",
        "payload": (
            "user: I am a research lead.\n"
            "user: That's wrong, use citation-backed claims instead.\n"
            "user: We decided to prioritize retrieval evaluation first.\n"
        ),
        "expect": {
            "IDENTITY.md": "research lead",
            "CORRECTIONS.md": "use citation-backed claims instead.",
            "DECISIONS.md": "prioritize retrieval evaluation first",
        },
    },
    {
        "name": "ops_json",
        "suffix": ".json",
        "payload": [
            {
                "role": "user",
                "content": (
                    "I work as an operations manager. "
                    "Please avoid long paragraphs. "
                    "Now we run handoffs twice daily."
                ),
            }
        ],
        "expect": {
            "IDENTITY.md": "operations manager",
            "PREFERENCES.md": "avoid long paragraphs.",
            "EVOLUTION.md": "now we run handoffs twice daily",
        },
    },
    {
        "name": "design_txt",
        "suffix": ".txt",
        "payload": (
            "user: I am a product designer.\n"
            "user: Do not guess user intent.\n"
            "user: I decided to validate with prototypes first.\n"
        ),
        "expect": {
            "IDENTITY.md": "product designer",
            "PREFERENCES.md": "do not guess user intent.",
            "DECISIONS.md": "validate with prototypes first",
        },
    },
]


@pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES])
def test_expanded_persona_end_to_end(fake_home: Path, tmp_path: Path, case: dict[str, object]):
    sample = tmp_path / f"{case['name']}{case['suffix']}"
    if case["suffix"] == ".json":
        sample.write_text(json.dumps(case["payload"]), encoding="utf-8")
    else:
        sample.write_text(str(case["payload"]), encoding="utf-8")

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

    analyze_res = runner.invoke(app, ["analyze", str(sample)])
    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

    mem = fake_home / "memory"
    expectations = case["expect"]
    assert isinstance(expectations, dict)
    for key, expected_phrase in expectations.items():
        filename = str(key).split("#", 1)[0]
        text = (mem / filename).read_text(encoding="utf-8").lower()
        assert str(expected_phrase).lower() in text
