"""Tests for the ``cerbero-bite healthcheck`` subcommand."""

from __future__ import annotations

from datetime import UTC, datetime, timedelta
from pathlib import Path

from click.testing import CliRunner

from cerbero_bite.cli import main as cli_main
from cerbero_bite.state import Repository, connect, run_migrations, transaction


def _seed_state(db: Path, *, last_check: datetime, kill_switch: bool = False) -> None:
    conn = connect(db)
    try:
        run_migrations(conn)
        repo = Repository()
        with transaction(conn):
            repo.init_system_state(
                conn, config_version="1.0.0", now=last_check
            )
            if kill_switch:
                repo.set_kill_switch(
                    conn, armed=True, reason="test", now=last_check
                )
            else:
                repo.touch_health_check(conn, now=last_check)
    finally:
        conn.close()


def test_healthcheck_exits_one_when_db_missing(tmp_path: Path) -> None:
    result = CliRunner().invoke(
        cli_main,
        ["healthcheck", "--db", str(tmp_path / "absent.sqlite")],
    )
    assert result.exit_code == 1
    assert "unhealthy" in result.output


def test_healthcheck_exits_one_when_kill_switch_armed(tmp_path: Path) -> None:
    db = tmp_path / "state.sqlite"
    _seed_state(db, last_check=datetime.now(UTC), kill_switch=True)
    result = CliRunner().invoke(cli_main, ["healthcheck", "--db", str(db)])
    assert result.exit_code == 1
    assert "kill switch" in result.output


def test_healthcheck_exits_one_when_last_check_stale(tmp_path: Path) -> None:
    db = tmp_path / "state.sqlite"
    _seed_state(db, last_check=datetime.now(UTC) - timedelta(hours=1))
    result = CliRunner().invoke(
        cli_main,
        ["healthcheck", "--db", str(db), "--max-staleness-s", "60"],
    )
    assert result.exit_code == 1
    assert "stale" in result.output


def test_healthcheck_exits_zero_on_recent_check(tmp_path: Path) -> None:
    db = tmp_path / "state.sqlite"
    _seed_state(db, last_check=datetime.now(UTC))
    result = CliRunner().invoke(cli_main, ["healthcheck", "--db", str(db)])
    assert result.exit_code == 0
    assert "healthy" in result.output
