#!/usr/bin/env python3
"""
autoprocess.py - CLI tool to process an audio file using a .json preset.

Usage:
    python tools/autoprocess.py input.wav preset.json [-o output.wav]
"""

import sys
import os
import json
import argparse
import warnings
from pathlib import Path

# Suppress annoying library warnings
warnings.filterwarnings("ignore", category=UserWarning, module="pkg_resources")
warnings.filterwarnings("ignore", message=".*pkg_resources is deprecated.*")

# Add src to sys.path to allow importing from engine
script_dir = Path(__file__).parent.absolute()
root_dir = script_dir.parent
src_dir = root_dir / "src"
sys.path.append(str(src_dir))

# Enable unbuffered output for real-time streaming
sys.stdout.reconfigure(line_buffering=True)

# Mock some UI dependencies if they are imported by engine (though they shouldn't be)
# Based on my analysis, engine.worker and engine.processor are safe.
try:
    from automaster_app.worker_pro import run_processing_pipeline
    from automaster_app.pipeline.orchestrator import _validate_genre
except ImportError as e:
    print(f"Error: Could not import worker_pro. {e}")
    sys.exit(1)

def main():
    parser = argparse.ArgumentParser(description="AutoRemaster CLI processing tool")
    parser.add_argument("input", help="Input audio file path")
    parser.add_argument("preset", help="Preset JSON file path")
    parser.add_argument("-o", "--output", help="Output audio file path (default: input_Mastered.wav)")
    parser.add_argument("-t", "--temp", default="temp", help="Temporary directory for stem separation")
    parser.add_argument("--legacy-chain", action="store_true",
                        help="Use the old processor_pro chain instead of the new pipeline")
    parser.add_argument("--no-stems", action="store_true",
                        help="Skip Phase A stem separation; master the original mix")
    parser.add_argument("--light", action="store_true",
                        help="Light mode: reduced per-stem processing depth")
    parser.add_argument("--genre", help="Select EDM Genre (Complextro, Psytrance, Melodic_Techno)")
    
    args = parser.parse_args()
    
    input_path = Path(args.input)
    preset_path = Path(args.preset)
    
    if not input_path.exists():
        print(f"Error: Input file not found: {args.input}")
        sys.exit(1)
        
    if not preset_path.exists():
        print(f"Error: Preset file not found: {args.preset}")
        sys.exit(1)
        
    # Load preset
    try:
        with open(preset_path, 'r') as f:
            preset = json.load(f)
    except Exception as e:
        print(f"Error: Failed to parse preset JSON: {e}")
        sys.exit(1)
        
    # Prepare output path
    if args.output:
        output_path = args.output
    else:
        output_path = str(input_path.parent / f"{input_path.stem}_Mastered.wav")
        
    # Extract active modules and order
    active_checkboxes = preset.get("active_modules", {})
    module_order = preset.get("module_order", None)
    
    # If active_modules is missing, use a default set or assume everything is false
    if not active_checkboxes:
        print("Warning: 'active_modules' not found in preset. No processing may be applied.")
        active_checkboxes = {}
        
    def log_callback(msg):
        print(f"[LOG] {msg}")
        
    def progress_callback(val):
        if isinstance(val, int):
            # Print progress every 1% for smoother bar
            print(f"[PROGRESS] {val}%")
        elif isinstance(val, dict) and val.get("type") == "stem_progress":
            pct = val.get("percent")
            msg = val.get("message")
            # More frequent stem updates
            print(f"[STEMS] {pct}%: {msg}")

    print(f"--- AutoRemaster CLI ---")
    print(f"Input:  {input_path.name}")
    print(f"Preset: {preset_path.name}")
    print(f"Output: {Path(output_path).name}")
    print(f"------------------------")
    
    # Ensure temp dir exists
    os.makedirs(args.temp, exist_ok=True)

    if args.genre:
        try:
            _validate_genre(args.genre)
        except ValueError as exc:
            print(f"Error: {exc}")
            sys.exit(1)

    try:
        run_processing_pipeline(
            file_path=str(input_path),
            output_path=output_path,
            preset=preset,
            active_checkboxes=active_checkboxes,
            custom_preset_values=preset, # Use the preset values as overrides
            tempo_factor=1.0,
            temp_dir=args.temp,
            progress_callback=progress_callback,
            log_callback=log_callback,
            module_order=module_order,
            legacy_chain=True if args.legacy_chain else None,
            genre=args.genre,
            no_stems=args.no_stems,
            light=args.light,
        )
        print(f"\nSUCCESS: Mastered file saved to: {output_path}")
    except ValueError as exc:
        print(f"Error: {exc}")
        sys.exit(1)
    except Exception as e:
        print(f"\nFAILED: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()
