import argparse
import sys
from pathlib import Path
from typing import Optional

from pyshield.scanner import Scanner
from pyshield.scoring_engine import ScoringEngine
from pyshield.report_builder import ReportBuilder
from pyshield.exporters.terminal_exporter import TerminalExporter
from pyshield.exporters.yaml_exporter import YamlExporter
from pyshield.exporters.markdown_exporter import MarkdownExporter

def main():
    parser = argparse.ArgumentParser(
        description="PyShield - Python-only deterministic security governance CLI"
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    scan_parser = subparsers.add_parser("scan", help="Scan a Python project directory")
    scan_parser.add_argument("path", type=str, help="Path to Python project directory")
    scan_parser.add_argument(
        "--format",
        type=str,
        default="terminal",
        choices=["terminal", "yaml", "markdown"],
        help="Output format",
    )
    scan_parser.add_argument(
        "--output", type=str, required=False, help="File path to save report"
    )

    args = parser.parse_args()

    if args.command == "scan":
        target_path = Path(args.path).resolve()
        
        if not target_path.exists() or not target_path.is_dir():
            print(f"Error: Invalid directory path: {target_path}", file=sys.stderr)
            sys.exit(1)

        # 1-4. Run Scanning
        scanner = Scanner(target_path)
        if not scanner.has_python_files():
            print("No Python files detected.", file=sys.stderr)
            sys.exit(0)

        raw_findings = scanner.run_scan()

        # 5-6. Run Scoring Engine
        scoring_engine = ScoringEngine(raw_findings)
        scoring_results = scoring_engine.calculate_scores()

        # 7. Build Report
        report_builder = ReportBuilder(target_path, raw_findings, scoring_results)
        final_report = report_builder.build()

        # 8. Export result
        if args.format == "terminal":
            exporter = TerminalExporter(final_report, args.output)
        elif args.format == "yaml":
            exporter = YamlExporter(final_report, args.output)
        elif args.format == "markdown":
            exporter = MarkdownExporter(final_report, args.output)
        else:
            print(f"Unsupported format: {args.format}", file=sys.stderr)
            sys.exit(1)

        exporter.export()

if __name__ == "__main__":
    main()
