from __future__ import annotations

from pathlib import Path

from typer.testing import CliRunner

from eightmem.cli.main import app
from eightmem.ui.app import create_app


runner = CliRunner()


def test_phase_flow_end_to_end(fake_home, tmp_path: Path):
    sample = tmp_path / "chat.json"
    sample.write_text(
        '[{"role":"user","content":"I am a product engineer. Please keep answers concise. '
        'We decided to launch a local-first CLI."}]',
        encoding="utf-8",
    )

    init_res = runner.invoke(app, ["init"])
    assert init_res.exit_code == 0
    assert "Runtime ready:" in init_res.stdout
    assert (fake_home / "memory" / "IDENTITY.md").exists()

    analyze_res = runner.invoke(app, ["analyze", str(sample)])
    assert analyze_res.exit_code == 0
    assert "Analyzed:" in analyze_res.stdout

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

    output = tmp_path / "compiled_context.md"
    export_res = runner.invoke(app, ["export-context", "-o", str(output)])
    assert export_res.exit_code == 0
    assert output.exists()
    assert "# 8mem Context Export" in output.read_text(encoding="utf-8")

    paths = {route.path for route in create_app().routes}
    assert "/" in paths
    assert "/files" in paths
    assert "/files/{name}" in paths
    assert "/analyze-upload" in paths


def test_phase_analyze_missing_file_returns_error(fake_home):
    result = runner.invoke(app, ["analyze", "missing-file.json"])
    assert result.exit_code == 1
    assert "Chat export not found:" in result.stdout
