from pathlib import Path

import typer

from songmatch.config import SongMatchConfig
from songmatch.pipeline import run
from songmatch.utils import setup_logging

app = typer.Typer(name="songmatch", help="Automated EQ matching between user audio and reference tracks.")


@app.command()
def process(
    user_audio: Path = typer.Argument(..., help="Path to the user's audio file (WAV, FLAC, MP3)"),
    reference_audio: Path = typer.Argument(..., help="Path to the reference audio file (WAV, FLAC, MP3)"),
    stems_match: bool = typer.Option(
        False,
        "--stems-match",
        help="Per-stem EQ matching. Splits both tracks into stems, matches EQ per stem, recombines.",
    ),
    mix_match: bool = typer.Option(
        False,
        "--mix-match",
        help="Full-mix EQ match via matchering. Uses full reference audio.",
    ),
    eq_smoothing: float = typer.Option(0.33, "--eq-smoothing", help="EQ smoothing in octave fractions. 0 = no smoothing."),
    eq_max_gain: float = typer.Option(12.0, "--eq-max-gain", help="Max EQ boost/cut in dB."),
    loudness_threshold: float = typer.Option(2.0, "--loudness-threshold", help="dB below peak LUFS to consider 'loud'."),
    min_segment: float = typer.Option(5.0, "--min-segment", help="Minimum crop segment duration in seconds."),
    max_segment: float = typer.Option(30.0, "--max-segment", help="Maximum crop segment duration in seconds."),
    dynamic_range_floor: float = typer.Option(4.0, "--dynamic-range-floor", help="Below this loudness range in dB, skip cropping."),
    model: str = typer.Option(
        "htdemucs_ft.yaml",
        "--model",
        help="audio-separator model filename.",
    ),
    output_sr: int = typer.Option(44100, "--output-sr", help="Output sample rate in Hz."),
    output_bits: int = typer.Option(16, "--output-bits", help="Output bit depth (16, 24, 32)."),
    keep_ref_stems: bool = typer.Option(False, "--keep-ref-stems", help="Keep reference stem temp files after processing."),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging."),
) -> None:
    """Process audio with automated EQ matching."""
    setup_logging(verbose=verbose)

    if not stems_match and not mix_match:
        typer.echo("Error: At least one of --stems-match or --mix-match must be specified.", err=True)
        raise typer.Exit(code=1)

    if not user_audio.exists():
        typer.echo(f"Error: User audio file not found: {user_audio}", err=True)
        raise typer.Exit(code=1)

    if not reference_audio.exists():
        typer.echo(f"Error: Reference audio file not found: {reference_audio}", err=True)
        raise typer.Exit(code=1)

    config = SongMatchConfig(
        user_audio=user_audio.resolve(),
        reference_audio=reference_audio.resolve(),
        stems_match=stems_match,
        mix_match=mix_match,
        eq_smoothing=eq_smoothing,
        eq_max_gain=eq_max_gain,
        loudness_threshold=loudness_threshold,
        min_segment=min_segment,
        max_segment=max_segment,
        dynamic_range_floor=dynamic_range_floor,
        model=model,
        output_sr=output_sr,
        output_bits=output_bits,
        keep_ref_stems=keep_ref_stems,
    )

    outputs = run(config)

    typer.echo("\nDone! Output files:")
    for path in outputs:
        typer.echo(f"  {path}")
