"""Tests offline para comfyui_critique_image_llm (impura: critica LLM-vision via ask_llm_vision).

Sin red, sin API: prueba el parser de JSON puro (_extract_json) y el flujo con ask_llm_vision
monkeypatcheado (veredicto estructurado, ambiguo->bad conservador, API caida, texto no parseable).
"""

import os
import sys

import pytest

sys.path.insert(0, os.path.dirname(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

import ml.comfyui_critique_image_llm as mod
from ml.comfyui_critique_image_llm import comfyui_critique_image_llm, _extract_json


def test_extract_json_fenced():
    txt = 'blah\n```json\n{"verdict": "good", "score": 8}\n```\nfin'
    assert _extract_json(txt) == {"verdict": "good", "score": 8}


def test_extract_json_brace_plano():
    assert _extract_json('  {"verdict": "bad", "score": 2}  ') == {"verdict": "bad", "score": 2}


def test_extract_json_sin_objeto_lanza():
    with pytest.raises(ValueError):
        _extract_json("no hay json aqui")


def _fake_vision(text, ok=True):
    return lambda user_prompt, image_path, **kw: {"ok": ok, "text": text, "error": "" if ok else "429"}


def test_flujo_veredicto_estructurado(monkeypatch):
    monkeypatch.setattr(mod, "ask_llm_vision",
                        _fake_vision('{"verdict": "good", "score": 8.5, "reasons": ["nitida"]}'))
    res = comfyui_critique_image_llm("i.png", "a cat")
    assert res["ok"] is True
    assert res["verdict"] == "good" and res["score_0_10"] == 8.5
    assert res["reasons"] == ["nitida"]


def test_verdict_ambiguo_cae_a_bad(monkeypatch):
    monkeypatch.setattr(mod, "ask_llm_vision",
                        _fake_vision('{"verdict": "maybe", "score": 5}'))
    res = comfyui_critique_image_llm("i.png", "p")
    assert res["ok"] is True and res["verdict"] == "bad"  # conservador ante ambiguo


def test_api_caida_ok_false(monkeypatch):
    monkeypatch.setattr(mod, "ask_llm_vision", _fake_vision("", ok=False))
    res = comfyui_critique_image_llm("i.png", "p")
    assert res["ok"] is False and res["error"]


def test_respuesta_no_parseable_ok_false(monkeypatch):
    monkeypatch.setattr(mod, "ask_llm_vision", _fake_vision("lo siento, no puedo"))
    res = comfyui_critique_image_llm("i.png", "p")
    assert res["ok"] is False and "no parseable" in res["error"]
