from __future__ import annotations

import sys
from pathlib import Path

from aws_guardrails.cli import main


def write_file(path: Path, content: str) -> Path:
    path.write_text(content, encoding="utf-8")
    return path


def test_cli_validates_single_policy_file(tmp_path: Path, monkeypatch, capsys):
    policy = write_file(
        tmp_path / "policy.json",
        """
        {
          "Version": "2012-10-17",
          "Statement": {
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::example-bucket"
          }
        }
        """,
    )

    monkeypatch.setattr(sys, "argv", ["aws-guardrails", "validate", str(policy)])

    exit_code = main()
    output = capsys.readouterr().out

    assert exit_code == 0
    assert f"PASS {policy} [iam]" in output
    assert "Summary: scanned 1 file(s), clean 1, warning-only 0, failed 0." in output


def test_cli_validates_mixed_directory(tmp_path: Path, monkeypatch, capsys):
    write_file(
        tmp_path / "policy.json",
        """
        {
          "Version": "2012-10-17",
          "Statement": {
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::example-bucket"
          }
        }
        """,
    )
    write_file(
        tmp_path / "template.yaml",
        """
        Resources:
          ExampleBucket:
            Type: AWS::S3::Bucket
        """,
    )
    write_file(
        tmp_path / "bad-policy.json",
        """
        {
          "Version": "2012-10-17",
          "Statement": {
            "Effect": "Allow",
            "Action": "ec2:CreateRole",
            "Resource": "*"
          }
        }
        """,
    )

    monkeypatch.setattr(sys, "argv", ["aws-guardrails", "validate", str(tmp_path)])

    exit_code = main()
    output = capsys.readouterr().out

    assert exit_code == 1
    assert f"FAIL {tmp_path / 'bad-policy.json'} [iam]" in output
    assert f"PASS {tmp_path / 'policy.json'} [iam]" in output
    assert f"PASS {tmp_path / 'template.yaml'} [cloudformation]" in output
    assert "Fix: Did you mean 'iam:CreateRole'?" in output
    assert "Summary: scanned 3 file(s), clean 2, warning-only 0, failed 1." in output


def test_cli_reports_missing_path(tmp_path: Path, monkeypatch, capsys):
    missing = tmp_path / "does-not-exist"
    monkeypatch.setattr(sys, "argv", ["aws-guardrails", "validate", str(missing)])

    exit_code = main()
    output = capsys.readouterr().out

    assert exit_code == 1
    assert f"FAIL {missing} [auto]" in output
    assert "FS002 Path does not exist." in output
