"""Tests for the Replay (birth story) feature."""

import json
import tempfile
from pathlib import Path

import pytest

from alive.core.replay import (
    BirthStory,
    BirthStoryRecorder,
    BuildAttemptRecord,
    display_birth_story,
    load_birth_story,
    save_birth_story,
)


@pytest.fixture
def tmp_skills_dir():
    with tempfile.TemporaryDirectory() as d:
        skill_dir = Path(d) / "test_skill"
        skill_dir.mkdir()
        (skill_dir / "skill.py").write_text("def run(): return {}")
        yield Path(d)


class TestBirthStoryRecorder:
    def test_records_attempts(self):
        recorder = BirthStoryRecorder("my_skill", "make a cool skill")
        recorder.record_attempt(1, "code1", success=False, error="NameError")
        recorder.record_attempt(2, "code2", success=True)
        story = recorder.finalize("used a different approach")

        assert story.skill_name == "my_skill"
        assert story.original_request == "make a cool skill"
        assert len(story.attempts) == 2
        assert story.attempts[0].test_result == "fail"
        assert story.attempts[0].error == "NameError"
        assert story.attempts[1].test_result == "pass"
        assert story.final_approach == "used a different approach"
        assert story.total_time_ms >= 0
        assert story.created_at != ""

    def test_empty_story(self):
        recorder = BirthStoryRecorder("empty", "nothing happened")
        story = recorder.finalize()
        assert len(story.attempts) == 0
        assert story.final_approach == ""


class TestSaveLoadBirthStory:
    def test_save_and_load_roundtrip(self, tmp_skills_dir):
        story = BirthStory(
            skill_name="test_skill",
            original_request="build a calculator",
            plan_step="math operations",
            attempts=[
                BuildAttemptRecord(1, "code_v1", "fail", error="TypeError"),
                BuildAttemptRecord(2, "code_v2", "pass"),
            ],
            total_time_ms=3500,
            final_approach="Fixed the type handling",
            created_at="2024-01-01T00:00:00Z",
        )

        path = save_birth_story(story, skills_dir=tmp_skills_dir)
        assert path.exists()

        loaded = load_birth_story("test_skill", skills_dir=tmp_skills_dir)
        assert loaded.skill_name == "test_skill"
        assert loaded.original_request == "build a calculator"
        assert len(loaded.attempts) == 2
        assert loaded.attempts[0].error == "TypeError"
        assert loaded.attempts[1].test_result == "pass"
        assert loaded.total_time_ms == 3500
        assert loaded.final_approach == "Fixed the type handling"

    def test_load_missing_raises(self, tmp_skills_dir):
        with pytest.raises(FileNotFoundError, match="No birth story found"):
            load_birth_story("nonexistent", skills_dir=tmp_skills_dir)

    def test_save_missing_skill_dir_raises(self, tmp_skills_dir):
        story = BirthStory(
            skill_name="ghost_skill",
            original_request="doesn't exist",
        )
        with pytest.raises(FileNotFoundError, match="Skill directory not found"):
            save_birth_story(story, skills_dir=tmp_skills_dir)


class TestDisplayBirthStory:
    def test_display_single_attempt(self, tmp_skills_dir, capsys):
        from rich.console import Console

        story = BirthStory(
            skill_name="quick_win",
            original_request="a quick skill",
            attempts=[BuildAttemptRecord(1, "def run(): return {}", "pass")],
            total_time_ms=1200,
            final_approach="Nailed it first try",
        )

        console = Console(file=open("/dev/null", "w"), force_terminal=False)
        # Just make sure it doesn't crash
        display_birth_story(story, console=console)

    def test_display_multi_attempt(self):
        from rich.console import Console

        story = BirthStory(
            skill_name="hard_one",
            original_request="a tricky skill",
            attempts=[
                BuildAttemptRecord(1, "bad code", "fail", error="SyntaxError: oops"),
                BuildAttemptRecord(2, "still bad", "fail", error="TypeError: wrong type"),
                BuildAttemptRecord(3, "def run(): return {'ok': True}", "pass"),
            ],
            total_time_ms=15000,
            final_approach="Third time's the charm",
        )

        console = Console(file=open("/dev/null", "w"), force_terminal=False)
        display_birth_story(story, console=console)
