"""skills/creador_trello.py — TRELLO EDITOR (estación 6)

Crear tarjeta Trello en board editor de videos con: cover producto + 6 mp4 + 6 PDFs brief.
Skill canónica: creador-trello-editor-videos.

Backend: Python puro (Trello API HTTP).
"""
from __future__ import annotations
import json
import urllib.parse
import urllib.request
from datetime import datetime
from pathlib import Path
from skills._lib import SkillContext, SkillResult

TRELLO_STATE_PATH = Path(r'C:/Users/ferna/.claude/state/trello.json')


def _load_trello_creds() -> dict:
    if TRELLO_STATE_PATH.exists():
        try:
            return json.loads(TRELLO_STATE_PATH.read_text(encoding='utf-8'))
        except Exception:
            return {}
    return {}


def run(inputs: dict, context: SkillContext) -> SkillResult:
    caja = context.read_caja()
    inp = caja.get('input_start', {})
    finalistas = (caja.get('sections', {}).get('comparador') or {}).get('finalistas') or []
    if len(finalistas) != 6:
        return SkillResult(ok=False, errors=[f'Esperaba 6 finalistas, hay {len(finalistas)}'])

    creds = _load_trello_creds()
    if not creds.get('api_key') or not creds.get('token'):
        return SkillResult(ok=False, errors=['Trello creds no encontrados en C:/Users/ferna/.claude/state/trello.json'])

    product = inp.get('product', 'Producto')
    country = inp.get('country', 'ES')
    saturated_label = 'SATURADO' if inp.get('saturated') else 'NO_SATURADO'
    today = datetime.now().strftime('%Y-%m-%d')
    name = f"Flow factory_v4 · {product} · {country} · {saturated_label} · {today}"

    desc_parts = [
        f"**Origen:** factory_v4 escalado de formato (5 similares + 1 arriesgado)",
        f"**Producto:** {product}",
        f"**País:** {country}",
        f"**Saturado:** {inp.get('saturated', False)}",
        f"**URL input:** {inp.get('video_url', '')}",
        "",
        "## Finalistas (5 similares + 1 arriesgado):",
    ]
    for f in finalistas:
        desc_parts.append(f"- #{f.get('rank')} **{f.get('tipo')}** · score {f.get('match_score', '?')} · {f.get('video_url', '')}")
    desc = '\n'.join(desc_parts)

    board_id = creds.get('videos_board_id', '69dfeaff21afd9a2e13bd708')
    list_id = creds.get('videos_list_id', '69dfeb002c3e1d314649ff84')

    params = urllib.parse.urlencode({
        'key': creds.get('api_key'),
        'token': creds.get('token'),
        'idList': list_id,
        'name': name,
        'desc': desc,
        'pos': 'top',
    })
    try:
        req = urllib.request.Request(f'https://api.trello.com/1/cards?{params}', method='POST')
        with urllib.request.urlopen(req, timeout=30) as r:
            card = json.loads(r.read().decode('utf-8'))
    except Exception as e:
        return SkillResult(ok=False, errors=[f'Trello create card falló: {e}'])

    output = {
        'card_id': card.get('id'),
        'short_url': card.get('shortUrl'),
        'name': card.get('name'),
        'attachments_count': 0,  # Stage 3: subir mp4 + PDFs de los 6 finalistas
        'note': 'STAGE 1: solo card creada con desc · attachments mp4/PDF en Stage 3',
    }
    context.write_section('trello_editor', output, mode='replace', actor='creador-trello-editor-videos')
    return SkillResult(ok=True, output=output)
