"""skills/interpretador.py — INTERPRETAR (estación 3)

Combo completo del ganador → strategy.json (queries + filtros para los 4 buscadores paralelos).
Skill canónica: interpretador-estrategia-busqueda.

Backend: claude CLI subprocess (LLM Opus 4.7 para diseñar estrategia).

Inputs:
  caja.analizar.combo_completo
  caja.input_start.{saturated, country}

Output:
  caja.sections.interpretar = {
    queries_fb: [..2..],
    queries_gethookd: [..2..],
    match_criteria: {...},
    cascada_paises: [country, 'UK', 'USA', 'AU', 'CA'] (REGLA #141 REFINADA msg 644),
    saturated_market, need_complex_videos, ...
  }
"""
from __future__ import annotations
from skills._lib import SkillContext, SkillResult
from .analizador_combo import extract_json_from_claude_output  # type: ignore


def run(inputs: dict, context: SkillContext) -> SkillResult:
    caja = context.read_caja()
    inp = caja.get('input_start', {})
    analyze = caja.get('sections', {}).get('analizar') or {}
    combo = analyze.get('combo_completo') or {}
    if not combo:
        return SkillResult(ok=False, errors=['caja.analizar.combo_completo vacío — ANALIZAR debió correr antes'])

    saturated = bool(inp.get('saturated', False))
    country_input = (inp.get('country') or 'ES').upper()

    prompt = build_strategy_prompt(combo, country_input, saturated, inp.get('product', ''))
    res = context.claude_cli(prompt, model='claude-opus-4-7', timeout_s=180)
    if not res.get('ok'):
        return SkillResult(ok=False, errors=[f'claude CLI falló: {res.get("stderr") or res.get("error")}'])

    strategy_raw = extract_json_from_claude_output(res.get('stdout', ''))

    # Refuerza REGLA #141 REFINADA msg 644: país input PRIMERO
    cascada = [country_input, 'UK', 'USA', 'AU', 'CA']
    # dedup preservando orden
    cascada = list(dict.fromkeys(cascada))

    strategy = {
        **strategy_raw,
        'saturated_market': saturated,
        'need_complex_videos': saturated,
        'cascada_paises': cascada,
        'min_candidates_per_buscador': 2,
        'max_retries_per_buscador': 5,
    }

    context.write_section('interpretar', strategy, mode='replace', actor='interpretador-estrategia-busqueda')
    return SkillResult(ok=True, output={'queries_fb_count': len(strategy.get('queries_fb', [])),
                                         'queries_gh_count': len(strategy.get('queries_gethookd', [])),
                                         'cascada_paises': cascada})


def build_strategy_prompt(combo: dict, country_input: str, saturated: bool, product: str) -> str:
    import json as _j
    combo_str = _j.dumps(combo, ensure_ascii=False, indent=2)
    sat_note = ('Mercado saturado: rechazar UGC talking-head básico problem→solution; aceptar VSL larga / advertorial / comparativas / storyselling / parodia / lifestyle / mecanismo / voz over apilada / demo dramático / vertical hook fuerte. Tendencia LARGOS con concepto elaborado.'
                if saturated else 'Mercado no saturado: aceptar también UGC simples.')
    return f"""Eres el agente INTERPRETADOR del flow Factory v4 escalado de formato (5 similares + 1 arriesgado).
Tu tarea: convertir el COMBO COMPLETO del video ganador en una ESTRATEGIA DE BÚSQUEDA accionable.

Combo del ganador:
{combo_str}

Contexto:
- País destino COD del producto: {country_input}
- Producto: {product}
- {sat_note}

Genera JSON estricto con esta estructura:
{{
  "queries_fb": [
    {{"buscador": "fb_1", "query": "<query 1 idioma país>", "filter_country": "{country_input}"}},
    {{"buscador": "fb_2", "query": "<query 2 alternativa diversificada>", "filter_country": "{country_input}"}}
  ],
  "queries_gethookd": [
    {{"buscador": "gh_1", "filters": {{"awareness": "<combo.awareness>", "scaled_days_min": 30, "scaled_days_max": 100, "country": ["{country_input}", "UK", "USA", "AU"]}}}},
    {{"buscador": "gh_2", "filters": {{"awareness": "<combo.awareness>", "category": "<categoría producto>", "format": "<formato_angulo>"}}}}
  ],
  "match_criteria": {{
    "awareness": "<combo.awareness>",
    "sofisticacion": [<sof-1>, <sof>, <sof+1>],
    "deseo_principal_keywords": ["<kw1>", "<kw2>"],
    "avatar_age_range": [<min>, <max>],
    "fuerza_cambio_signals": ["<s1>", "<s2>"],
    "exclude_formats": ["UGC talking-head básico problem→solution"]
  }}
}}

REGLAS DURAS:
- País input ({country_input}) PRIMERO en cualquier filtro country (REGLA #141 REFINADA msg 644)
- DIVERSIFICAR queries — fb_1 ≠ fb_2 lingüística/semánticamente
- gh_1 enfoca en awareness + scaled_days · gh_2 enfoca en categoría + formato

Responde SOLO con el JSON."""
