"""CLI collect auto-read behavior tests.

Spec source: cli-refactor.enhance-collect-auto-read.
"""

from datetime import datetime, timezone
from pathlib import Path

from click.testing import CliRunner
from returns.result import Success

from anima.core.schemas import (
    AgentResult,
    AgentState,
    AgentStateData,
    JobSpec,
    TokenUsage,
)
from anima.shell.cli import main
from anima.shell.state import (
    create_agent_state,
    read_state,
    write_result,
    write_state,
)


def _create_completed_agent(instance_id: str) -> AgentStateData:
    """Create and persist a completed test agent."""
    create_result = create_agent_state(
        instance_id=instance_id,
        persona_name="test-persona",
        job=JobSpec(persona_ref="test@test", instance_id=instance_id),
    )
    assert isinstance(create_result, Success), (
        f"Failed to create agent state: {create_result.failure()}"
    )
    state = create_result.unwrap()

    completed_state = AgentStateData(
        **{
            **state.model_dump(),
            "state": AgentState.completed,
            "updated_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    state_result = write_state(state.agent_id, completed_state, "finish", {})
    assert isinstance(state_result, Success), (
        f"Failed to write state: {state_result.failure()}"
    )

    read_result = read_state(state.agent_id)
    assert isinstance(read_result, Success), (
        f"Failed to read state: {read_result.failure()}"
    )
    return read_result.unwrap()


def test_collect_displays_inline_result_content_for_file_path(
    tmp_state_dir: Path,
    tmp_path: Path,
) -> None:
    """Collect displays file content inline when result_ref is a local path."""
    runner = CliRunner()
    completed_agent = _create_completed_agent("inst_collect_file")

    result_file = tmp_path / "collect-output.txt"
    result_file.write_text("inline result payload", encoding="utf-8")

    write_result_outcome = write_result(
        completed_agent.agent_id,
        AgentResult(
            final_state=AgentState.completed,
            token_usage=TokenUsage(prompt_tokens=3, completion_tokens=7),
            result_ref=str(result_file),
        ),
    )
    assert isinstance(write_result_outcome, Success), (
        f"Failed to write result: {write_result_outcome.failure()}"
    )

    collect_result = runner.invoke(
        main,
        ["collect", completed_agent.agent_id],
        env={"ANIMA_STATE": str(tmp_state_dir)},
    )

    assert collect_result.exit_code == 0
    assert "Result Content:" in collect_result.output
    assert "inline result payload" in collect_result.output


def test_collect_preserves_non_file_result_ref_behavior(tmp_state_dir: Path) -> None:
    """Collect keeps existing output when result_ref is not a file path."""
    runner = CliRunner()
    completed_agent = _create_completed_agent("inst_collect_uri")

    write_result_outcome = write_result(
        completed_agent.agent_id,
        AgentResult(
            final_state=AgentState.completed,
            token_usage=TokenUsage(prompt_tokens=4, completion_tokens=6),
            result_ref="s3://bucket/path/result.json",
        ),
    )
    assert isinstance(write_result_outcome, Success), (
        f"Failed to write result: {write_result_outcome.failure()}"
    )

    collect_result = runner.invoke(
        main,
        ["collect", completed_agent.agent_id],
        env={"ANIMA_STATE": str(tmp_state_dir)},
    )

    assert collect_result.exit_code == 0
    assert "s3://bucket/path/result.json" in collect_result.output
    assert "Result Content:" not in collect_result.output
