from __future__ import annotations

import json

import pytest
from click.testing import CliRunner

from agentlint import cli

ERROR_DIFF = """diff --git a/app.py b/app.py
--- a/app.py
+++ b/app.py
@@ -1 +1,2 @@
 print("ok")
+password = "supersecret123"
"""

WARNING_DIFF = """diff --git a/requirements.txt b/requirements.txt
--- a/requirements.txt
+++ b/requirements.txt
@@ -1 +1,2 @@
 requests==2.0.0
+flask==3.0.0
"""


def test_integration_json_schema_keys() -> None:
    runner = CliRunner()
    result = runner.invoke(cli.main, ["check", "--stdin", "--format", "json"], input=WARNING_DIFF)
    payload = json.loads(result.output)
    assert set(payload.keys()) == {"version", "metadata", "summary", "findings"}
    assert {"version", "timestamp"} <= set(payload["metadata"])
    assert {"total", "by_severity"} <= set(payload["summary"])
    assert all({"check", "severity", "message", "file", "line"} <= set(item) for item in payload["findings"])


def test_integration_markdown_structure() -> None:
    runner = CliRunner()
    result = runner.invoke(cli.main, ["check", "--stdin", "--format", "markdown"], input=WARNING_DIFF)
    assert result.exit_code == 1
    assert result.output.startswith("# agentlint Report")
    assert "| Check | Severity | Count |" in result.output
    assert "<details><summary><code>requirements.txt</code>" in result.output
    assert "Generated by [agentlint](https://github.com/mordecai/agentlint)." in result.output


def test_integration_exit_codes_clean_and_error() -> None:
    runner = CliRunner()
    clean = runner.invoke(cli.main, ["check", "--stdin"], input="")
    assert clean.exit_code == 0

    failing = runner.invoke(cli.main, ["check", "--stdin"], input=ERROR_DIFF)
    assert failing.exit_code == 1


@pytest.mark.parametrize("output_format", ["text", "json", "markdown"])
def test_integration_empty_diff_clean_output_all_formats(output_format: str) -> None:
    runner = CliRunner()
    result = runner.invoke(cli.main, ["check", "--stdin", "--format", output_format], input="")
    assert result.exit_code == 0

    if output_format == "json":
        payload = json.loads(result.output)
        assert payload["summary"] == {
            "total": 0,
            "by_severity": {"error": 0, "warning": 0, "info": 0},
        }
        assert payload["findings"] == []
    elif output_format == "markdown":
        assert result.output.startswith("# agentlint Report")
        assert "No findings." in result.output
    else:
        assert "errors=0 warnings=0 info=0" in result.output
