# tests/test_openapi_contract.py
from __future__ import annotations

from pathlib import Path

import pytest

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


def test_openapi_strict_fails_if_empty(repo_ctx, ux, monkeypatch):
    repo = repo_ctx.repo
    # 空にする
    _write(repo / "contracts" / "openapi.json", "")

    write_aiguard_yml(repo)

    # guard/dlp は素通り
    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)

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

    assert ex.value.code == 1
    report = read_json(repo / "ai_check_report.json")
    assert report["status"] == "fail"
    assert "empty" in (report["openapi_contract"] or "")


def test_openapi_strict_passes_if_valid(repo_ctx, ux, monkeypatch):
    repo = repo_ctx.repo
    _write(repo / "contracts" / "openapi.json", '{"openapi":"3.0.0","info":{"title":"t","version":"1"}}')

    write_aiguard_yml(repo)

    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)
    monkeypatch.setattr(cli, "run_shell", lambda *a, **k: cli.subprocess.CompletedProcess(a[0], 0, stdout="ok\n", stderr=""))
    monkeypatch.setattr(cli, "run_shell_stream", lambda *a, **k: cli.subprocess.CompletedProcess(a[0], 0, stdout="ok\n", stderr=""))

    cli.cmd_check(ux, repo, strict=True)

    report = read_json(repo / "ai_check_report.json")
    assert report["status"] == "pass"
    assert report["openapi_contract"] is None
