# tests/test_check_timeouts.py
from __future__ import annotations

from pathlib import Path

import pytest

import oceansguard.cli as cli
from tests.conftest import read_json, write_aiguard_yml


def test_check_records_timeout_and_fails(repo_ctx, ux, monkeypatch):
    repo = repo_ctx.repo
    write_aiguard_yml(repo)

    # guard/dlp/openapi を素通り
    def fake_run_argv(argv, cwd, check=False, timeout=None):
        if argv[:2] == ["git", "diff"] and "--numstat" in argv:
            return cli.subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
        if argv[:2] == ["git", "ls-files"]:
            return cli.subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
        return cli.subprocess.CompletedProcess(argv, 0, stdout="", stderr="")

    monkeypatch.setattr(cli, "run_argv", fake_run_argv)

    # 最初のコマンドでタイムアウトさせる
    def fake_run_shell(cmd: str, cwd: Path, check: bool = False, timeout: int | None = None):
        raise cli.subprocess.TimeoutExpired(cmd=cmd, timeout=timeout or 1)

    monkeypatch.setattr(cli, "run_shell", fake_run_shell)
    # streaming は呼ばれない想定だが念のため
    monkeypatch.setattr(cli, "run_shell_stream", lambda *a, **k: cli.subprocess.CompletedProcess(a[0], 0, stdout="", stderr=""))

    with pytest.raises(SystemExit) as ex:
        cli.cmd_check(ux, repo, strict=False)

    assert ex.value.code == 1

    report = read_json(repo / "ai_check_report.json")
    assert report["status"] == "fail"
    assert report["checks"][0]["exit_code"] == 124
    assert report["checks"][0]["timeout"] is True

    log_txt = (repo / "ai_test_last.log").read_text(encoding="utf-8")
    assert "[TIMEOUT]" in log_txt
