#!/usr/bin/env python3
"""
CLI module for Vulnerability Checker.
"""

import argparse
import json
import sys
from pathlib import Path
from typing import List, Optional, Dict, Any

from rich.console import Console
from rich.table import Table

from vulnerability_checker.checker import VulnerabilityChecker
from vulnerability_checker.models import VulnerabilityReport, CheckStatus


def parse_arguments() -> argparse.Namespace:
    """
    Parse command line arguments.
    """
    parser = argparse.ArgumentParser(
        description="Check Python code for vulnerabilities."
    )
    parser.add_argument(
        "-V", "--version",
        action="store_true",
        help="Show version and exit",
    )
    parser.add_argument(
        "path",
        type=str,
        nargs="?",
        help="Path to directory or file for checking",
    )
    parser.add_argument(
        "--output",
        "-o",
        type=str,
        help="Path to save the report in JSON format",
    )
    parser.add_argument(
        "--checks",
        type=str,
        help="Comma-separated list of checks (e.g.: sql-injection,xss,dependency-check)",
    )
    parser.add_argument(
        "--verbose",
        "-v",
        action="store_true",
        help="Detailed output",
    )
    parser.add_argument(
        "--exit-zero",
        action="store_true",
        help="Always return 0 exit code, even when vulnerabilities are found",
    )
    parser.add_argument(
        "--config",
        type=str,
        help="Path to configuration file",
    )
    return parser.parse_args()


def display_report(report: VulnerabilityReport, verbose: bool = False) -> None:
    """
    Display report in the terminal.
    
    Args:
        report: Scan report
        verbose: Detailed output
    """
    console = Console()
    
    console.print(f"\n[bold]Vulnerability Checker Report[/bold]")
    console.print(f"Scan: {report.target_path}")
    console.print(f"Date: {report.scan_date}")
    console.print(f"Vulnerabilities found: [bold red]{report.total_issues}[/bold red]")
    
    if report.total_issues == 0:
        console.print("\n[bold green]No vulnerabilities detected![/bold green]")
        return
    
    # Results table
    table = Table(title="Detected Vulnerabilities")
    table.add_column("Type", style="cyan")
    table.add_column("File", style="blue")
    table.add_column("Line", style="yellow")
    table.add_column("Severity", style="red")
    table.add_column("Description", style="white")
    
    for issue in report.issues:
        table.add_row(
            issue.issue_type,
            issue.file_path,
            str(issue.line_number),
            issue.severity.upper(),
            issue.description
        )
        
    console.print(table)
    
    # Statistics table
    stats_table = Table(title="Check Statistics")
    stats_table.add_column("Check", style="cyan")
    stats_table.add_column("Status", style="green")
    stats_table.add_column("Issues found", style="red")
    
    for check, status in report.checks_status.items():
        status_color = "green" if status.status == CheckStatus.PASSED else "red"
        stats_table.add_row(
            check,
            f"[{status_color}]{status.status.value}[/{status_color}]",
            str(status.issues_count)
        )
    
    console.print(stats_table)


def save_json_report(report: VulnerabilityReport, output_path: str) -> None:
    """
    Save report in JSON format.
    
    Args:
        report: Scan report
        output_path: Path to save the report
    """
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(report.to_dict(), f, ensure_ascii=False, indent=2)


def print_version() -> None:
    """
    Print the current version of the package.
    """
    from vulnerability_checker import __version__
    print(__version__)


def main() -> int:
    """
    Main CLI function.
    
    Returns:
        Return code (0 - success, 1 - vulnerabilities found, 2 - path does not exist)
    """
    args = parse_arguments()
    if getattr(args, "version", False):
        print_version()
        return 0
    if not args.path:
        print("Error: path is required")
        return 2
    target_path = Path(args.path)
    if not target_path.exists():
        print(f"Error: path {args.path} does not exist")
        return 2
    
    # List of checks
    checks_list = None
    if args.checks:
        checks_list = args.checks.split(",")
    
    # Create checker instance
    checker = VulnerabilityChecker(
        config_path=args.config,
    )
    
    # Run scan
    report = checker.run(
        target_path=str(target_path),
        checks=checks_list,
        verbose=args.verbose,
    )
    
    # Display report
    display_report(report, args.verbose)
    
    # Save report if path specified
    if args.output:
        save_json_report(report, args.output)
        print(f"\nReport saved to {args.output}")
    
    # Return exit code
    if args.exit_zero:
        return 0
    
    return 1 if report.total_issues > 0 else 0


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