"""
optik CLI - Command line interface for model analysis.
"""

import argparse
import sys
from pathlib import Path


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="optik",
        description="The optical lens for AI model interpretability",
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Available commands")
    
    # analyze command
    analyze_parser = subparsers.add_parser("analyze", help="Analyze model on images")
    analyze_parser.add_argument("model", help="Path to model file (e.g., best.pt)")
    analyze_parser.add_argument("--images", "-i", required=True, help="Path to image or directory")
    analyze_parser.add_argument("--output", "-o", default="report.html", help="Output report path")
    analyze_parser.add_argument("--methods", "-m", nargs="+", 
                                default=["detection_flow", "grid_trace"],
                                help="Analysis methods to run")
    
    # version command
    parser.add_argument("--version", "-v", action="store_true", help="Show version")
    
    args = parser.parse_args()
    
    if args.version:
        from optik import __version__
        print(f"optik {__version__}")
        return 0
    
    if args.command == "analyze":
        return run_analyze(args)
    
    parser.print_help()
    return 0


def run_analyze(args):
    """Run analysis command."""
    from optik import Optik
    from optik.utils import load_image, create_detection_overlay, save_image
    
    print(f"Loading model: {args.model}")
    analyzer = Optik.from_yolo(args.model)
    
    image_path = Path(args.images)
    if image_path.is_dir():
        images = list(image_path.glob("*.jpg")) + list(image_path.glob("*.png"))
    else:
        images = [image_path]
    
    all_results = []
    for img_path in images:
        print(f"Analyzing: {img_path}")
        results = analyzer.analyze(str(img_path), methods=args.methods)
        all_results.append(results)
    
    # Generate report
    output_path = Path(args.output)
    if len(all_results) == 1:
        analyzer.report(all_results[0], str(output_path))
    else:
        # For multiple images, create individual reports
        for i, results in enumerate(all_results):
            out = output_path.parent / f"{output_path.stem}_{i}{output_path.suffix}"
            analyzer.report(results, str(out))
    
    print(f"Report saved: {args.output}")
    return 0


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