"""Core OpenCV-free video download, crop detection, and composition logic for web_app."""

from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any
from urllib.parse import urlparse

import numpy as np
from PIL import Image

APP_DIR = Path(__file__).resolve().parent


def find_binary(name: str) -> str:
    """Resolve binary across app bin/, local skill bin/, PATH, standard dirs, and imageio_ffmpeg fallback."""
    candidates = [
        APP_DIR / "bin" / name,
        APP_DIR.parent / ".agents" / "skills" / "video-generator" / "bin" / name,
        Path.home() / ".local" / "bin" / name,
    ]
    for cand in candidates:
        if cand.exists() and os.access(cand, os.X_OK):
            return str(cand)
    found = shutil.which(name)
    if found:
        return found
    for sys_dir in ("/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"):
        cand = Path(sys_dir) / name
        if cand.exists() and os.access(cand, os.X_OK):
            return str(cand)
    if name == "ffmpeg":
        try:
            import imageio_ffmpeg  # type: ignore

            exe = imageio_ffmpeg.get_ffmpeg_exe()
            if exe and Path(exe).exists():
                return exe
        except Exception:
            pass
    raise FileNotFoundError(
        f"Required binary '{name}' not found. Run setup_shared_hosting.sh or install '{name}' on PATH."
    )


def run_cmd(cmd: list[str], timeout: int = 180) -> subprocess.CompletedProcess[str]:
    proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
    if proc.returncode != 0:
        err = (proc.stderr or proc.stdout or "").strip()
        raise RuntimeError(f"Command failed ({proc.returncode}): {err[-600:]}")
    return proc


def probe_media(path: str | Path) -> dict[str, Any]:
    """Probe width, height, fps, duration, and audio using ffprobe (or ffmpeg fallback)."""
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(f"Media not found: {p}")

    try:
        ffprobe = find_binary("ffprobe")
        proc = run_cmd(
            [ffprobe, "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", str(p)],
            timeout=30,
        )
        info = json.loads(proc.stdout or "{}")
        streams = info.get("streams", [])
        vs = next((s for s in streams if s.get("codec_type") == "video"), None)
        aus = next((s for s in streams if s.get("codec_type") == "audio"), None)
        fmt = info.get("format", {})
        dur = float(fmt.get("duration") or (vs or {}).get("duration") or 0.0)
        fps = 30.0
        if vs and vs.get("r_frame_rate") and "/" in vs["r_frame_rate"]:
            n, d = vs["r_frame_rate"].split("/", 1)
            if float(d) > 0:
                fps = round(float(n) / float(d), 3)
        return {
            "width": int(vs["width"]) if vs else 1080,
            "height": int(vs["height"]) if vs else 1920,
            "fps": fps,
            "duration": round(dur, 3),
            "has_audio": aus is not None,
            "size_bytes": p.stat().st_size,
        }
    except FileNotFoundError:
        ffmpeg = find_binary("ffmpeg")
        proc = subprocess.run([ffmpeg, "-i", str(p)], capture_output=True, text=True, timeout=30)
        txt = proc.stderr or ""
        m_dim = re.search(r"Video:.*?,\s*(\d{2,5})x(\d{2,5})", txt)
        m_fps = re.search(r"(\d+(?:\.\d+)?)\s*fps", txt)
        m_dur = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", txt)
        dur = 0.0
        if m_dur:
            dur = int(m_dur.group(1)) * 3600 + int(m_dur.group(2)) * 60 + float(m_dur.group(3))
        return {
            "width": int(m_dim.group(1)) if m_dim else 1080,
            "height": int(m_dim.group(2)) if m_dim else 1920,
            "fps": float(m_fps.group(1)) if m_fps else 30.0,
            "duration": round(dur, 3),
            "has_audio": "Audio:" in txt,
            "size_bytes": p.stat().st_size,
        }


def load_image_rgb(path: Path) -> Image.Image:
    """Load standard images via Pillow or HEIC/other formats via FFmpeg fallback."""
    try:
        return Image.open(path).convert("RGB")
    except Exception:
        ffmpeg = find_binary("ffmpeg")
        with tempfile.TemporaryDirectory() as tmpdir:
            png = Path(tmpdir) / "decoded.png"
            run_cmd([ffmpeg, "-y", "-hide_banner", "-loglevel", "error", "-i", str(path), "-frames:v", "1", "-update", "1", str(png)])
            return Image.open(png).convert("RGB")


def fit_cover_image(img: Image.Image, target_w: int, target_h: int) -> Image.Image:
    src_w, src_h = img.size
    scale = max(target_w / src_w, target_h / src_h)
    nw = max(target_w, int(round(src_w * scale)))
    nh = max(target_h, int(round(src_h * scale)))
    resized = img.resize((nw, nh), Image.Resampling.LANCZOS)
    left = (nw - target_w) // 2
    top = (nh - target_h) // 2
    return resized.crop((left, top, left + target_w, top + target_h))


def prepare_zoomed_background(
    bg_path: Path,
    width: int = 1080,
    height: int = 1920,
    zoom: float = 1.45,
    y_offset_frac: float = 0.425,
) -> Image.Image:
    """Zoom and crop background so the lower subject head stays clearly visible below the video box."""
    img = load_image_rgb(bg_path)
    src_w, src_h = img.size
    zoom = max(1.0, min(3.0, float(zoom)))
    y_offset_frac = max(0.0, min(1.0, float(y_offset_frac)))
    scaled_w = int(round(width * zoom))
    scaled_h = int(round(src_h * (scaled_w / src_w)))
    if scaled_h < height:
        scaled_h = height
        scaled_w = int(round(src_w * (scaled_h / src_h)))
    resized = img.resize((scaled_w, scaled_h), Image.Resampling.LANCZOS)
    x0 = max(0, (scaled_w - width) // 2)
    max_y0 = max(0, scaled_h - height)
    y0 = max(0, min(max_y0, int(round(max_y0 * y_offset_frac))))
    return resized.crop((x0, y0, x0 + width, y0 + height))


def sample_frames_ffmpeg(video_path: Path, n_samples: int = 6) -> tuple[np.ndarray, int, int]:
    """Extract evenly spaced BGR float32 frames via FFmpeg without requiring OpenCV."""
    meta = probe_media(video_path)
    w, h = int(meta["width"]), int(meta["height"])
    dur = max(1.0, float(meta["duration"] or 10.0))
    fps_rate = max(0.2, n_samples / max(1.0, dur * 0.9))
    ffmpeg = find_binary("ffmpeg")
    proc = subprocess.run(
        [
            ffmpeg, "-hide_banner", "-loglevel", "error",
            "-i", str(video_path),
            "-vf", f"fps={fps_rate:.4f}",
            "-frames:v", str(n_samples),
            "-f", "rawvideo", "-pix_fmt", "bgr24", "-",
        ],
        capture_output=True,
        timeout=60,
    )
    if proc.returncode != 0 or not proc.stdout:
        raise RuntimeError(f"Failed to sample frames: {proc.stderr.decode('utf-8', 'replace')}")
    frame_bytes = w * h * 3
    count = len(proc.stdout) // frame_bytes
    if count < 1:
        raise RuntimeError("No video frames decoded from input")
    arr = np.frombuffer(proc.stdout[: count * frame_bytes], dtype=np.uint8).reshape((count, h, w, 3)).astype(np.float32)
    return arr, w, h


def detect_main_crop(video_path: Path, inset_px: int = 4) -> tuple[int, int, int, int]:
    """Auto-detect the active inner video box inside static meme wrappers or letterbox bars."""
    stack, w, h = sample_frames_ffmpeg(video_path, n_samples=6)
    if stack.shape[0] < 2:
        return (0, 0, w - (w % 2), h - (h % 2))

    temporal_std = np.std(stack, axis=0).mean(axis=2)  # (h, w)
    active = temporal_std > 4.2

    row_frac = active.mean(axis=1)
    active_rows = row_frac > 0.12
    best_span: tuple[int, int] = (0, h - 1)
    best_len = 0
    cur_start: int | None = None
    for y in range(h):
        if active_rows[y]:
            if cur_start is None:
                cur_start = y
        else:
            if cur_start is not None:
                if y + 6 < h and np.any(active_rows[y : y + 6]):
                    continue
                if (y - 1 - cur_start) > best_len:
                    best_len = y - 1 - cur_start
                    best_span = (cur_start, y - 1)
                cur_start = None
    if cur_start is not None and (h - 1 - cur_start) > best_len:
        best_len = h - 1 - cur_start
        best_span = (cur_start, h - 1)

    if best_len < int(h * 0.15):
        return (0, 0, w - (w % 2), h - (h % 2))

    y0, y1 = best_span
    col_frac = active[y0 : y1 + 1, :].mean(axis=0)
    xs = np.where(col_frac > 0.12)[0]
    if len(xs) < int(w * 0.2):
        x0, x1 = 0, w - 1
    else:
        x0, x1 = int(xs[0]), int(xs[-1])

    # Expand past still interior zones (e.g. webcam wall) using same-row side margins + temporal gate.
    mid_bgr = stack[stack.shape[0] // 2]
    corner_std = float(
        np.mean(
            [
                temporal_std[:24, :24].mean(),
                temporal_std[:24, max(0, w - 24) :].mean(),
                temporal_std[max(0, h - 24) :, :24].mean(),
                temporal_std[max(0, h - 24) :, max(0, w - 24) :].mean(),
            ]
        )
    )
    if x0 >= 32 and (w - 1 - x1) >= 32 and corner_std < 2.2:
        side_samples = np.concatenate([mid_bgr[:, :24, :], mid_bgr[:, w - 24 :, :]], axis=1)
        row_bg_med = np.median(side_samples, axis=1)
        row_bg_spread = np.maximum(
            36.0,
            np.percentile(np.linalg.norm(side_samples - row_bg_med[:, None, :], axis=2), 95, axis=1) * 1.35,
        )

        def _is_fg_row(ny: int) -> bool:
            if float(np.mean(temporal_std[ny, x0 : x1 + 1] > 2.2)) < 0.12:
                return False
            row_dist = np.linalg.norm(mid_bgr[ny, x0 : x1 + 1, :] - row_bg_med[ny], axis=1)
            return float(np.mean(row_dist > row_bg_spread[ny])) > 0.50

        for step in (-1, 1):
            gap = 0
            ny = (y0 - 1) if step == -1 else (y1 + 1)
            while 0 <= ny < h:
                if _is_fg_row(ny):
                    if step == -1:
                        y0 = ny
                    else:
                        y1 = ny
                    gap = 0
                else:
                    gap += 1
                    if gap >= 4:
                        break
                ny += step

        top_bot_samples = np.concatenate([mid_bgr[:24, :, :], mid_bgr[h - 24 :, :, :]], axis=0)
        col_bg_med = np.median(top_bot_samples, axis=0)
        col_bg_spread = np.maximum(
            36.0,
            np.percentile(np.linalg.norm(top_bot_samples - col_bg_med[None, :, :], axis=2), 95, axis=0) * 1.35,
        )

        def _is_fg_col(nx: int) -> bool:
            if float(np.mean(temporal_std[y0 : y1 + 1, nx] > 2.2)) < 0.12:
                return False
            col_dist = np.linalg.norm(mid_bgr[y0 : y1 + 1, nx, :] - col_bg_med[nx], axis=1)
            return float(np.mean(col_dist > col_bg_spread[nx])) > 0.50

        for step in (-1, 1):
            gap = 0
            nx = (x0 - 1) if step == -1 else (x1 + 1)
            while 0 <= nx < w:
                if _is_fg_col(nx):
                    if step == -1:
                        x0 = nx
                    else:
                        x1 = nx
                    gap = 0
                else:
                    gap += 1
                    if gap >= 4:
                        break
                nx += step

    cx0 = min(max(0, x0 + inset_px), w - 64)
    cy0 = min(max(0, y0 + inset_px), h - 64)
    cw = max(64, (x1 - x0 + 1) - inset_px * 2)
    ch = max(64, (y1 - y0 + 1) - inset_px * 2)
    cw -= cw % 2
    ch -= ch % 2
    return (cx0, cy0, cw, ch)


def validate_video_url(url: str) -> str:
    parsed = urlparse(url.strip())
    if parsed.scheme not in ("http", "https") or not parsed.netloc:
        raise ValueError("Please enter a valid http:// or https:// video link.")
    host = parsed.netloc.lower()
    if host.startswith("localhost") or host.startswith("127.") or host.startswith("169.254.") or host.startswith("10.") or host.startswith("192.168."):
        raise ValueError("Local/private network URLs are not allowed.")
    return url.strip()


def extract_shortcode(url: str) -> str:
    m = re.search(r"instagram\.com/(?:reel|reels|p|tv)/([A-Za-z0-9_-]+)", url)
    if m:
        return m.group(1)
    return "rebranded_video"


def _resolve_ytdlp_cmd() -> list[str]:
    """Return yt-dlp command list using binary if present or `python -m yt_dlp` fallback."""
    try:
        return [find_binary("yt-dlp")]
    except FileNotFoundError:
        import importlib.util

        if importlib.util.find_spec("yt_dlp") is not None:
            return [sys.executable, "-m", "yt_dlp"]
        raise


def download_video_url(url: str, out_dir: Path) -> tuple[Path, str]:
    """Download video from Instagram or supported URL via yt-dlp, ensuring merged video+audio MP4."""
    clean_url = validate_video_url(url)
    shortcode = extract_shortcode(clean_url)
    ytdlp_cmd = _resolve_ytdlp_cmd()
    ffmpeg = find_binary("ffmpeg")
    # Pass exact ffmpeg directory when standard binary name exists, else pass full binary path.
    ffmpeg_loc = str(Path(ffmpeg).parent) if Path(ffmpeg).name == "ffmpeg" else ffmpeg
    out_dir.mkdir(parents=True, exist_ok=True)
    out_tmpl = str(out_dir / f"{shortcode}.%(ext)s")
    run_cmd(
        [
            *ytdlp_cmd,
            "--no-playlist",
            "--ffmpeg-location",
            ffmpeg_loc,
            "-f",
            "bv*+ba/b",
            "--merge-output-format",
            "mp4",
            "-o",
            out_tmpl,
            clean_url,
        ],
        timeout=180,
    )
    mp4 = out_dir / f"{shortcode}.mp4"
    if mp4.exists() and mp4.stat().st_size > 1000:
        return mp4, shortcode

    # Fallback: if yt-dlp downloaded separate dash video & audio files (e.g. without ffprobe), merge via ffmpeg.
    files = [p for p in out_dir.iterdir() if p.is_file() and p.stat().st_size > 100]
    video_only = sorted(
        [p for p in files if p.suffix.lower() in (".mp4", ".webm", ".mkv", ".mov")],
        key=lambda p: p.stat().st_size,
        reverse=True,
    )
    audio_only = sorted(
        [p for p in files if p.suffix.lower() in (".m4a", ".mp3", ".aac", ".opus", ".ogg", ".wav")],
        key=lambda p: p.stat().st_size,
        reverse=True,
    )
    if video_only and audio_only:
        run_cmd(
            [
                ffmpeg, "-y", "-hide_banner", "-loglevel", "error",
                "-i", str(video_only[0]),
                "-i", str(audio_only[0]),
                "-map", "0:v:0", "-map", "1:a:0",
                "-c", "copy", "-shortest",
                str(mp4),
            ],
            timeout=120,
        )
        if mp4.exists() and mp4.stat().st_size > 1000:
            return mp4, shortcode
    if video_only:
        return video_only[0], shortcode
    raise FileNotFoundError("Download completed but no video stream file was produced.")


def compose_video(
    input_video: Path,
    background_path: Path,
    output_path: Path,
    cover_path: Path | None = None,
    preview_jpg_path: Path | None = None,
    crop_rect: tuple[int, int, int, int] | None = None,
    bg_zoom: float = 1.45,
    bg_y_frac: float = 0.425,
    pip_width: int = 928,
    pip_y: int = 410,
    max_pip_bottom: int = 1155,
    max_pip_height: int = 980,
    include_cover_frame: bool = True,
) -> dict[str, Any]:
    """Crop main area from input video, overlay onto zoomed background, and emit clean 30fps CFR MP4."""
    width, height = 1080, 1920
    fps = 30
    meta = probe_media(input_video)
    cx, cy, cw, ch = crop_rect or detect_main_crop(input_video)

    scale = min(pip_width / cw, max_pip_height / ch)
    pip_w = max(64, int(round(cw * scale)))
    pip_h = max(64, int(round(ch * scale)))
    pip_w -= pip_w % 2
    pip_h -= pip_h % 2
    pip_x = (width - pip_w) // 2
    cur_pip_y = max(90, min(pip_y, max_pip_bottom - pip_h))

    ffmpeg = find_binary("ffmpeg")
    output_path.parent.mkdir(parents=True, exist_ok=True)
    tmp_out = output_path.with_suffix(".tmp.mp4")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmp = Path(tmpdir)
        bg_png = tmp / "bg.png"
        prepare_zoomed_background(
            background_path,
            width=width,
            height=height,
            zoom=bg_zoom,
            y_offset_frac=bg_y_frac,
        ).save(bg_png)

        cov_png: Path | None = None
        if cover_path and include_cover_frame:
            cov_png = tmp / "cover.png"
            fit_cover_image(load_image_rgb(cover_path), width, height).save(cov_png)

        cmd = [ffmpeg, "-y", "-hide_banner", "-loglevel", "error"]
        if cov_png:
            frame_dur = 1.0 / fps
            cmd.extend([
                "-loop", "1", "-t", f"{frame_dur * 2:.6f}", "-i", str(cov_png),
                "-loop", "1", "-i", str(bg_png),
                "-i", str(input_video),
            ])
            fc = [
                f"[2:v]crop={cw}:{ch}:{cx}:{cy},scale={pip_w}:{pip_h}:flags=lanczos,fps={fps},setsar=1[fg]",
                f"[1:v][fg]overlay={pip_x}:{cur_pip_y}:shortest=1,format=yuv420p[main_v]",
                f"[0:v]fps={fps},setsar=1,format=yuv420p,trim=end_frame=1[cov_v]",
                "[cov_v][main_v]concat=n=2:v=1:a=0[vout]",
            ]
            audio_idx = 2
        else:
            cmd.extend(["-loop", "1", "-i", str(bg_png), "-i", str(input_video)])
            fc = [
                f"[1:v]crop={cw}:{ch}:{cx}:{cy},scale={pip_w}:{pip_h}:flags=lanczos,fps={fps},setsar=1[fg]",
                f"[0:v][fg]overlay={pip_x}:{cur_pip_y}:shortest=1,format=yuv420p[vout]",
            ]
            audio_idx = 1

        if meta["has_audio"]:
            if cov_png:
                delay_ms = int(round(1000.0 / fps))
                fc.append(f"[{audio_idx}:a]adelay={delay_ms}|{delay_ms}[aout]")
            else:
                fc.append(f"[{audio_idx}:a]anull[aout]")

        cmd.extend(["-filter_complex", ";".join(fc), "-map", "[vout]"])
        if meta["has_audio"]:
            cmd.extend(["-map", "[aout]", "-c:a", "aac", "-ar", "44100", "-ac", "2", "-b:a", "128k"])
        else:
            cmd.append("-an")

        cmd.extend([
            "-r", str(fps), "-fps_mode", "cfr", "-video_track_timescale", "30000",
            "-c:v", "libx264", "-preset", "fast", "-crf", "19",
            "-profile:v", "high", "-level:v", "4.0", "-pix_fmt", "yuv420p",
            "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709",
            "-movflags", "+faststart",
            str(tmp_out),
        ])
        run_cmd(cmd, timeout=300)

    tmp_out.replace(output_path)

    if preview_jpg_path:
        mid_t = max(0.3, float(meta["duration"] or 2.0) * 0.5)
        run_cmd([
            ffmpeg, "-y", "-hide_banner", "-loglevel", "error",
            "-ss", f"{mid_t:.2f}", "-i", str(output_path),
            "-frames:v", "1", "-q:v", "3", "-update", "1", str(preview_jpg_path),
        ])

    out_meta = probe_media(output_path)
    out_meta["detected_crop"] = {"x": cx, "y": cy, "w": cw, "h": ch}
    out_meta["pip_box"] = {"x": pip_x, "y": cur_pip_y, "w": pip_w, "h": pip_h}
    return out_meta
