"""Leise Hintergrundmusik für VidPuls-Promo-Videos."""

from __future__ import annotations

import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BGM_DIR = ROOT / "assets" / "promo"
BGM_FILE = BGM_DIR / "ambient_lofi.mp3"


def _ffmpeg() -> str | None:
    try:
        from jam.tiktok_remix import _find_ffmpeg

        return _find_ffmpeg()
    except ImportError:
        return None


def ensure_bgm_path(*, min_sec: float = 90.0) -> Path | None:
    """Sanfte Ambient-Spur (lokal gecacht, royalty-free generiert)."""
    BGM_DIR.mkdir(parents=True, exist_ok=True)
    if BGM_FILE.is_file() and BGM_FILE.stat().st_size > 5000:
        return BGM_FILE

    ff = _ffmpeg()
    if not ff:
        return None

    dur = max(75.0, min_sec + 15.0)
    try:
        subprocess.run(
            [
                ff, "-y",
                "-f", "lavfi", "-i", f"sine=frequency=110:duration={dur:.1f}",
                "-f", "lavfi", "-i", f"sine=frequency=165:duration={dur:.1f}",
                "-f", "lavfi", "-i", f"anoisesrc=d={dur:.1f}:c=pink:a=0.008",
                "-filter_complex",
                (
                    "[0:a][1:a]amix=inputs=2:duration=first,volume=0.35[pad];"
                    "[2:a]lowpass=f=500,volume=0.25[noise];"
                    "[pad][noise]amix=inputs=2:duration=first,"
                    "lowpass=f=1200,highpass=f=90,volume=0.22,"
                    f"afade=t=in:st=0:d=2.5,afade=t=out:st={dur - 2.5:.1f}:d=2.5"
                ),
                "-c:a", "libmp3lame", "-q:a", "4", str(BGM_FILE),
            ],
            capture_output=True,
            timeout=120,
            check=True,
        )
        return BGM_FILE if BGM_FILE.is_file() else None
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
        return None


def mix_voice_with_bgm(
    voice: Path,
    out: Path,
    *,
    duration_sec: float,
    music_volume: float = 0.14,
) -> bool:
    """Voice + leise Musik → eine Audiospur."""
    if not voice.is_file():
        return False
    bgm = ensure_bgm_path(min_sec=duration_sec)
    ff = _ffmpeg()
    if not ff or not bgm:
        return False

    out.parent.mkdir(parents=True, exist_ok=True)
    dur = max(1.0, duration_sec)
    vol = max(0.06, min(0.22, music_volume))
    try:
        subprocess.run(
            [
                ff, "-y",
                "-i", str(voice),
                "-i", str(bgm),
                "-filter_complex",
                (
                    f"[0:a]apad=whole_dur={dur:.2f},atrim=0:{dur:.2f},volume=1.0[voice];"
                    f"[1:a]aloop=loop=-1:size=2e+09,atrim=0:{dur:.2f},volume={vol:.3f}[bgm];"
                    "[voice][bgm]amix=inputs=2:duration=first:dropout_transition=2[aout]"
                ),
                "-map", "[aout]",
                "-c:a", "libmp3lame", "-q:a", "2",
                str(out),
            ],
            capture_output=True,
            timeout=180,
            check=True,
        )
        return out.is_file() and out.stat().st_size > 500
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
        return False
