#!/usr/bin/env python3
"""
FREEEXILE INDEPENDENT SECURITY & ANTI-CHEAT AUDIT CLI TOOL
Command-line Interface for the Independent Security Division (SEC-OPS).

Executes end-to-end security penetration testing, economic anomaly auditing,
client attestation validation, and enforces the Security Veto Gate for CI/CD builds.

Usage:
    python tools/security/run_independent_security_audit.py [--build-id <BUILD_ID>] [--env <STAGING|PROD>] [--json-out <PATH>]
"""

import argparse
import os
import sys
import json

# Ensure utf-8 encoding on Windows console
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8")

# Ensure server module is discoverable
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
SERVER_DIR = os.path.join(PROJECT_ROOT, "server")
if SERVER_DIR not in sys.path:
    sys.path.insert(0, SERVER_DIR)

from security.independent_security_auditor import (
    IndependentSecurityAuditor,
    AuditReportStatus,
    SeverityLevel
)


def parse_arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="FreeExile Independent Security & Anti-Cheat Audit CLI"
    )
    parser.add_argument(
        "--build-id",
        type=str,
        default="v2026.1-STAGING",
        help="Build version or Git commit SHA to audit"
    )
    parser.add_argument(
        "--env",
        type=str,
        default="STAGING",
        choices=["STAGING", "PRODUCTION", "LOCAL"],
        help="Target runtime environment"
    )
    parser.add_argument(
        "--json-out",
        type=str,
        default=None,
        help="Optional path to write full JSON audit report"
    )
    return parser.parse_args()


def main() -> int:
    args = parse_arguments()
    print("=" * 70)
    print("🛡️  FREEEXILE INDEPENDENT SECURITY & ANTI-CHEAT OPERATIONS DIVISION")
    print(f"🔒 Initiating Autonomous Independent Security Audit for: {args.build_id}")
    print(f"🌐 Target Environment: {args.env}")
    print("=" * 70)

    auditor = IndependentSecurityAuditor()
    report = auditor.execute_full_security_audit(
        build_version=args.build_id,
        environment=args.env
    )

    print("\n" + report.to_markdown() + "\n")

    if args.json_out:
        out_data = {
            "audit_id": report.audit_id,
            "build_version": report.build_version,
            "environment": report.environment,
            "status": report.status.value,
            "tests_executed": report.tests_executed,
            "critical_count": report.critical_count,
            "high_count": report.high_count,
            "medium_count": report.medium_count,
            "low_count": report.low_count,
            "timestamp": report.timestamp
        }
        with open(args.json_out, "w", encoding="utf-8") as f:
            json.dump(out_data, f, indent=2)
        print(f"📁 Audit report written to: {args.json_out}")

    if report.status == AuditReportStatus.VETOED:
        print("❌ SECURITY VETO GATE TRIGGERED: Build is REJECTED by Independent Security Division!")
        return 1
    else:
        print("✅ SECURITY RELEASE GATE PASSED: Zero Critical/High vulnerabilities detected.")
        return 0


if __name__ == "__main__":
    sys.exit(main())
