#!/usr/bin/env python3
"""Detached background worker for a single video rebranding job."""

from __future__ import annotations

import json
import sys
import traceback
from pathlib import Path
from typing import Any

APP_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(APP_DIR))

from processor import compose_video, download_video_url  # noqa: E402


def write_status(job_dir: Path, payload: dict[str, Any]) -> None:
    tmp = job_dir / "status.json.tmp"
    target = job_dir / "status.json"
    tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    tmp.replace(target)


def parse_crop(raw: str | None) -> tuple[int, int, int, int] | None:
    if not raw or not raw.strip():
        return None
    parts = [int(p.strip()) for p in raw.strip().split(":")]
    if len(parts) != 4:
        raise ValueError("Manual crop must use format W:H:X:Y")
    cw, ch, cx, cy = parts
    return (max(0, cx), max(0, cy), max(64, cw - (cw % 2)), max(64, ch - (ch % 2)))


def run_job(job_dir: Path) -> None:
    cfg = json.loads((job_dir / "config.json").read_text(encoding="utf-8"))
    source_url = (cfg.get("url") or "").strip()
    uploaded_video = cfg.get("uploaded_video")
    bg_path = Path(cfg["background_path"])
    cover_path = Path(cfg["cover_path"]) if cfg.get("cover_path") else None
    include_cover = bool(cfg.get("include_cover", True))
    bg_zoom = float(cfg.get("bg_zoom", 1.45))
    bg_y_frac = float(cfg.get("bg_y_frac", 0.425))
    crop_rect = parse_crop(cfg.get("manual_crop"))

    try:
        if uploaded_video:
            src_video = Path(uploaded_video)
            shortcode = cfg.get("source_name") or Path(src_video).stem or "uploaded_video"
        elif source_url:
            write_status(
                job_dir,
                {
                    "status": "running",
                    "step": "downloading",
                    "progress": 20,
                    "message": "Downloading video from link...",
                },
            )
            src_video, shortcode = download_video_url(source_url, job_dir / "download")
        else:
            raise ValueError("No video link or uploaded video provided.")

        write_status(
            job_dir,
            {
                "status": "running",
                "step": "rendering",
                "progress": 60,
                "message": "Cropping main area and compositing 1080x1920 video...",
                "shortcode": shortcode,
            },
        )

        out_mp4 = job_dir / "output.mp4"
        preview_jpg = job_dir / "preview.jpg"
        meta = compose_video(
            input_video=src_video,
            background_path=bg_path,
            output_path=out_mp4,
            cover_path=cover_path,
            preview_jpg_path=preview_jpg,
            crop_rect=crop_rect,
            bg_zoom=bg_zoom,
            bg_y_frac=bg_y_frac,
            include_cover_frame=include_cover,
        )

        # Clean up large raw download inside job folder after rendering to keep disk tidy.
        if (job_dir / "download").exists():
            for f in (job_dir / "download").glob("*"):
                f.unlink(missing_ok=True)
        if uploaded_video and Path(uploaded_video).exists():
            Path(uploaded_video).unlink(missing_ok=True)

        write_status(
            job_dir,
            {
                "status": "done",
                "step": "done",
                "progress": 100,
                "message": "Ready to preview and download!",
                "shortcode": shortcode,
                "download_name": f"{shortcode}_rebranded.mp4",
                "duration": meta["duration"],
                "width": meta["width"],
                "height": meta["height"],
                "fps": meta["fps"],
                "has_audio": meta["has_audio"],
                "size_bytes": meta["size_bytes"],
                "detected_crop": meta["detected_crop"],
                "pip_box": meta["pip_box"],
            },
        )
    except Exception as exc:
        write_status(
            job_dir,
            {
                "status": "error",
                "step": "error",
                "progress": 100,
                "error": str(exc),
                "trace": traceback.format_exc(limit=4),
            },
        )
        sys.exit(1)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: worker.py <job_dir>", file=sys.stderr)
        sys.exit(1)
    run_job(Path(sys.argv[1]))
