#!/usr/bin/env python3
"""Command-line interface for IDA Pro batch decompiler."""

import argparse
import sys
from pathlib import Path

from .core import IDABatchDecompiler


def main():
    parser = argparse.ArgumentParser(
        description="IDA Pro Batch Decompiler - Batch decompile binaries to C code",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  ida-decompile -i ./binaries -o ./output
  ida-decompile -i /path/to/binary -o ./decompiled -p /Applications/IDA\\ Professional\\ 9.1.app/Contents/MacOS/idat
  ida-decompile -i ./binaries -o ./output -j 8 -t 600
        """
    )

    parser.add_argument(
        '-i', '--input-dir',
        required=True,
        help='Input directory or binary file path'
    )
    parser.add_argument(
        '-o', '--output-dir',
        required=True,
        help='Output directory for C files'
    )
    parser.add_argument(
        '-p', '--idat-path',
        default='/Applications/IDA Professional 9.1.app/Contents/MacOS/idat',
        help='Path to idat executable (default: /Applications/IDA Professional 9.1.app/Contents/MacOS/idat)'
    )
    parser.add_argument(
        '-j', '--jobs',
        type=int,
        default=4,
        help='Number of parallel processes (default: 4)'
    )
    parser.add_argument(
        '-t', '--timeout',
        type=int,
        default=300,
        help='Timeout per file in seconds (default: 300)'
    )
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='Show verbose output'
    )
    parser.add_argument(
        '--version',
        action='store_true',
        help='Show version'
    )

    args = parser.parse_args()

    if args.version:
        from . import __version__
        print(f"ida-decompile version {__version__}")
        return

    # Validate idat path
    idat_path = Path(args.idat_path)
    if not idat_path.exists():
        print(f"ERROR: idat not found at {idat_path}", file=sys.stderr)
        sys.exit(1)

    # Validate input
    input_path = Path(args.input_dir)
    if not input_path.exists():
        print(f"ERROR: Input path not found: {input_path}", file=sys.stderr)
        sys.exit(1)

    # Create output directory
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # Initialize decompiler
    decompiler = IDABatchDecompiler(
        idat_path=str(idat_path),
        output_dir=str(output_dir),
        jobs=args.jobs,
        timeout=args.timeout,
        verbose=args.verbose
    )

    print(f"\n{'=' * 60}")
    print("IDA Pro Batch Decompiler")
    print(f"{'=' * 60}")
    print(f"\nInput: {input_path}")
    print(f"Output: {output_dir}")
    print(f"IDAT: {idat_path}")
    print(f"Jobs: {args.jobs}")
    print(f"Timeout: {args.timeout}s")
    print()

    # Process files
    if input_path.is_file():
        # Single file
        binary_name = input_path.stem
        print(f"Processing single file: {binary_name}")
        success, message = decompiler.decompile_binary(str(input_path))
        status = "OK" if success else "FAIL"
        print(f"[{status}] {binary_name}: {message}")
        success_count = 1 if success else 0
        fail_count = 0 if success else 1
    else:
        # Directory scan - use BinaryScanner directly for more control
        from .discovery import BinaryScanner

        scanner = BinaryScanner()
        binaries = scanner.find_binaries(input_path)

        if not binaries:
            print("\nNo binary files found.")
            return

        print(f"Found {len(binaries)} binary file(s)\n")

        # Start processing
        print(f"{'=' * 60}")
        print("Starting decomposition...")
        print(f"{'=' * 60}\n")

        success_count = 0
        fail_count = 0

        if args.jobs > 1 and len(binaries) > 1:
            # Parallel processing
            results = decompiler.decompile_batch([str(b) for b in binaries], parallel=True)
            for binary_path, (success, msg) in results.items():
                bin_name = Path(binary_path).name
                status = "OK" if success else "FAIL"
                print(f"[{status}] {bin_name}: {msg}")
                if success:
                    success_count += 1
                else:
                    fail_count += 1
        else:
            # Sequential processing
            for binary in binaries:
                success, msg = decompiler.decompile_binary(str(binary))
                status = "OK" if success else "FAIL"
                print(f"[{status}] {binary.name}: {msg}")
                if success:
                    success_count += 1
                else:
                    fail_count += 1

    # Summary
    print(f"\n{'=' * 60}")
    print("Processing complete!")
    print(f"{'=' * 60}")
    print(f"Success: {success_count}")
    print(f"Failed: {fail_count}")
    print(f"Total: {success_count + fail_count}")
    print(f"\nOutput directory: {output_dir}")


if __name__ == "__main__":
    main()
