"""Tests offline para comfyui_update_skill_score (impura, sin red).

- golden: media incremental correcta tras varios juicios; reescribe in-place sin crear
  snapshots ni growth_log,
- edge: arranca desde score_mean/score_n ausentes (skill recién creada),
- error: skill inexistente / score no numérico → ok=False.
"""

import json
import os
import sys

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

import pytest  # noqa: E402

from ml.comfyui_update_skill_score import comfyui_update_skill_score  # noqa: E402


def _seed(lib, slug="demo", **extra):
    sdir = os.path.join(lib, slug)
    os.makedirs(sdir, exist_ok=True)
    recipe = {"schema_version": 1, "slug": slug, "version": "1.0.0",
              "base_workflow": "txt2img", **extra}
    with open(os.path.join(sdir, "recipe.json"), "w", encoding="utf-8") as f:
        json.dump(recipe, f)
    return sdir


def test_golden_media_incremental(tmp_path):
    lib = str(tmp_path)
    sdir = _seed(lib, score_mean=0.0, score_n=0)

    r1 = comfyui_update_skill_score("demo", 7.0, library_dir=lib)
    assert r1["ok"] and r1["score_n"] == 1 and r1["score_mean"] == 7.0

    r2 = comfyui_update_skill_score("demo", 8.0, library_dir=lib)
    assert r2["score_n"] == 2 and r2["score_mean"] == 7.5

    r3 = comfyui_update_skill_score("demo", 6.0, library_dir=lib)
    assert r3["score_n"] == 3
    assert abs(r3["score_mean"] - 7.0) < 1e-9  # (7+8+6)/3

    # in-place: ni versions/ ni growth_log creados por este helper.
    assert not os.path.exists(os.path.join(sdir, "versions"))
    assert not os.path.exists(os.path.join(sdir, "growth_log.jsonl"))

    with open(os.path.join(sdir, "recipe.json"), encoding="utf-8") as f:
        cur = json.load(f)
    assert cur["score_n"] == 3


def test_edge_sin_campos_previos(tmp_path):
    lib = str(tmp_path)
    _seed(lib, slug="fresh")  # sin score_mean/score_n
    res = comfyui_update_skill_score("fresh", 9.0, library_dir=lib)
    assert res["ok"] and res["score_mean"] == 9.0 and res["score_n"] == 1
    assert res["prev_score_n"] == 0


def test_error_skill_inexistente(tmp_path):
    res = comfyui_update_skill_score("nope", 5.0, library_dir=str(tmp_path))
    assert res["ok"] is False and "no encontrada" in res["error"]


def test_error_score_no_numerico(tmp_path):
    lib = str(tmp_path)
    _seed(lib, slug="x", score_mean=0.0, score_n=0)
    res = comfyui_update_skill_score("x", "siete", library_dir=lib)
    assert res["ok"] is False and "numérico" in res["error"]


if __name__ == "__main__":
    sys.exit(pytest.main([__file__, "-q"]))
