# tests/test_dlp_detection.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_dlp_blocks_on_detect(repo_ctx, ux, monkeypatch):
    repo = repo_ctx.repo
    # 疑似トークンを含む tracked ファイル
    _write(repo / "backend" / "app" / "secrets.txt", "token='ghp_abcdefghijklmnopqrstuvwxyz0123456789ABCD'\n")

    write_aiguard_yml(repo, enable_dlp=True, block_on_detect=True, mask=True)

    # git ls-files が secrets.txt を返すようにする（実gitに依存しない）
    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="backend/app/secrets.txt\n", 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=False)

    assert ex.value.code == 1

    report = read_json(repo / "ai_check_report.json")
    assert report["status"] == "fail"
    assert report["dlp_hits"]
    # mask 有効なので <masked:...> 形式になる
    assert "<masked:" in report["dlp_hits"][0]


def test_dlp_allowlist_skips_file(repo_ctx, ux, monkeypatch):
    repo = repo_ctx.repo
    _write(repo / "backend" / "app" / "secrets.txt", "token='ghp_abcdefghijklmnopqrstuvwxyz0123456789ABCD'\n")

    # allowlist 付きにしたいので yml を手で上書き（簡易）
    write_aiguard_yml(repo, enable_dlp=True, block_on_detect=True, mask=True)
    yml = (repo / ".aiguard.yml").read_text(encoding="utf-8")
    yml = yml.replace("allowlist_files: []", "allowlist_files:\n    - \"backend/app/secrets.txt\"")
    (repo / ".aiguard.yml").write_text(yml, encoding="utf-8")

    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="backend/app/secrets.txt\n", stderr="")
        return cli.subprocess.CompletedProcess(argv, 0, stdout="", stderr="")

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

    # checks 自体は全部 OK にする
    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=False)

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