"""skills/descargador_video.py — DESCARGAR (estación 1)

Bajar el video del enlace input. yt-dlp primario, Playwright Chrome CDP fallback.
Skill canónica: descargador-video-escalado (.claude/agents/escalado_formatos/descargador-video-escalado.md).

Backend: Python puro (yt-dlp subprocess).

Inputs esperados (de caja.input_start):
  - video_url (str): URL del video a descargar
  - product (str): nombre del producto (para output dir)
  - country (str): país target

Output:
  caja.sections.descargar = {
    'video_path': str (absoluto),
    'size_bytes': int,
    'source_method': 'yt-dlp' | 'playwright_cdp' | 'cache_hit',
    'cache_hit': bool,
  }
"""
from __future__ import annotations
import subprocess
from pathlib import Path
from skills._lib import SkillContext, SkillResult


def run(inputs: dict, context: SkillContext) -> SkillResult:
    inp = context.read_caja().get('input_start', {})
    url = inp.get('video_url') or inputs.get('video_url')
    product = inp.get('product', 'unknown')
    if not url:
        return SkillResult(ok=False, errors=['video_url no proporcionada en caja.input_start'])

    out_dir = context.run_dir
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / 'video.mp4'

    # PASO 1: cache lookup
    if out_path.exists() and out_path.stat().st_size > 100_000:
        size = out_path.stat().st_size
        context.write_section('descargar', {
            'video_path': str(out_path),
            'size_bytes': size,
            'size_kb': size // 1024,
            'source_method': 'cache_hit',
            'cache_hit': True,
        }, mode='replace', actor='descargador-video')
        return SkillResult(ok=True, output={'video_path': str(out_path), 'cache_hit': True})

    # PASO 2: yt-dlp directo
    try:
        r = subprocess.run(
            ['yt-dlp', '-f', 'best[ext=mp4]/best', '-o', str(out_path), url],
            capture_output=True, text=True, timeout=180
        )
        if r.returncode == 0 and out_path.exists() and out_path.stat().st_size > 100_000:
            size = out_path.stat().st_size
            context.write_section('descargar', {
                'video_path': str(out_path),
                'size_bytes': size,
                'size_kb': size // 1024,
                'source_method': 'yt-dlp',
                'cache_hit': False,
            }, mode='replace', actor='descargador-video')
            return SkillResult(ok=True, output={'video_path': str(out_path), 'size_kb': size // 1024})
        # yt-dlp falló — necesitaría Playwright fallback (no implementado en MVP)
        return SkillResult(
            ok=False,
            errors=[f'yt-dlp falló: rc={r.returncode}', r.stderr[-300:]],
            metadata={'fallback_pending': 'playwright_cdp'},
        )
    except subprocess.TimeoutExpired:
        return SkillResult(ok=False, errors=['yt-dlp timeout 180s'])
    except FileNotFoundError:
        return SkillResult(ok=False, errors=['yt-dlp no instalado en PATH'])
