from __future__ import annotations

from pathlib import Path

from typer.testing import CliRunner

from eightmem.cli.main import app


runner = CliRunner()


def test_analyze_fails_for_missing_file(fake_home: Path):
    init_res = runner.invoke(app, ["init"])
    assert init_res.exit_code == 0

    missing = fake_home / "does-not-exist.json"
    res = runner.invoke(app, ["analyze", str(missing)])
    assert res.exit_code == 1
    assert "Chat export not found" in res.stdout


def test_analyze_fails_for_malformed_json(fake_home: Path, tmp_path: Path):
    init_res = runner.invoke(app, ["init"])
    assert init_res.exit_code == 0

    bad = tmp_path / "bad.json"
    bad.write_text('{"role":"user","content":"hello"', encoding="utf-8")

    res = runner.invoke(app, ["analyze", str(bad)])
    assert res.exit_code == 1
    assert "Analyze failed:" in res.stdout


def test_analyze_fails_for_invalid_encoding(fake_home: Path, tmp_path: Path):
    init_res = runner.invoke(app, ["init"])
    assert init_res.exit_code == 0

    bad = tmp_path / "bad.txt"
    bad.write_bytes(b"\xff\xfe\x00\x00bad-encoding")

    res = runner.invoke(app, ["analyze", str(bad)])
    assert res.exit_code == 1
    assert "Analyze failed:" in res.stdout


def test_analyze_empty_file_is_safe(fake_home: Path, tmp_path: Path):
    init_res = runner.invoke(app, ["init"])
    assert init_res.exit_code == 0

    empty = tmp_path / "empty.txt"
    empty.write_text("", encoding="utf-8")

    res = runner.invoke(app, ["analyze", str(empty)])
    assert res.exit_code == 0
    assert "Analyzed:" in res.stdout
    assert "+0 new entries" in res.stdout

