from __future__ import annotations

import argparse
import json
from pathlib import Path

from aws_guardrails.validators import DocumentKind, validate_path


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="aws-guardrails")
    subparsers = parser.add_subparsers(dest="command", required=True)

    validate_parser = subparsers.add_parser("validate", help="Validate IAM policies or CloudFormation templates.")
    validate_parser.add_argument("paths", nargs="+", help="Files or directories to validate.")
    validate_parser.add_argument(
        "--kind",
        choices=("auto", "iam", "cloudformation"),
        default="auto",
        help="Document kind to validate.",
    )
    validate_parser.add_argument(
        "--format",
        choices=("text", "json"),
        default="text",
        help="Output format.",
    )
    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    results = []
    for raw_path in args.paths:
        path = Path(raw_path)
        results.extend(validate_path(path, kind=args.kind))

    if args.format == "json":
        print(_render_json(results))
    else:
        print(_render_text(results))

    return 0 if all(result.is_valid for result in results) else 1


def _render_text(results) -> str:
    lines: list[str] = []
    for result in results:
        status = "PASS" if result.is_valid else "FAIL"
        lines.append(f"{status} {result.path} [{result.document_type}]")
        for issue in result.issues:
            location = issue.location()
            lines.append(f"  - {issue.severity} {issue.code}{location} {issue.message}")
            if issue.suggestion:
                lines.append(f"    Fix: {issue.suggestion}")
    lines.append("")
    lines.append(_render_summary(results))
    return "\n".join(lines)


def _render_json(results) -> str:
    payload = []
    for result in results:
        payload.append(
            {
                "path": str(result.path),
                "document_type": result.document_type,
                "is_valid": result.is_valid,
                "issues": [
                    {
                        "code": issue.code,
                        "severity": issue.severity,
                        "message": issue.message,
                        "line": issue.line,
                        "column": issue.column,
                        "suggestion": issue.suggestion,
                    }
                    for issue in result.issues
                ],
            }
        )
    return json.dumps(payload, indent=2)


def _render_summary(results) -> str:
    clean = sum(1 for result in results if result.is_valid and not result.issues)
    warning_only = sum(1 for result in results if result.is_valid and result.issues)
    failed = sum(1 for result in results if not result.is_valid)
    return f"Summary: scanned {len(results)} file(s), clean {clean}, warning-only {warning_only}, failed {failed}."


if __name__ == "__main__":
    raise SystemExit(main())
