"""Tests de comfyui_export_asset_to_godot (offline; sin Godot real, reimport mockeado)."""

import os
import sys

import numpy as np
from PIL import Image

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from pipelines.comfyui_export_asset_to_godot import comfyui_export_asset_to_godot  # noqa: E402


def _godot_proj(tmp_path):
    """Crea un proyecto Godot 4 minimo (solo project.godot)."""
    proj = tmp_path / "godot_proj"
    proj.mkdir()
    (proj / "project.godot").write_text(
        'config_version=5\n\n[application]\n\nconfig/name="Test"\n', encoding="utf-8"
    )
    return str(proj)


def _png(tmp_path, name="hero_00001_.png"):
    p = tmp_path / name
    Image.fromarray(np.zeros((16, 16, 3), np.uint8), "RGB").save(str(p))
    return str(p)


def test_golden_pixelart(tmp_path):
    proj = _godot_proj(tmp_path)
    asset = _png(tmp_path)
    res = comfyui_export_asset_to_godot(asset, "pixelart", proj, reimport=False)
    assert res["ok"] is True, res["error"]
    # copiado a sprites/ con nombre limpio
    assert res["dest_res_path"] == "res://assets/sprites/hero.png"
    assert os.path.isfile(os.path.join(proj, "assets", "sprites", "hero.png"))
    # .import textura con Lossless + Nearest global del proyecto
    imp = open(res["import_path"], encoding="utf-8").read()
    assert 'importer="texture"' in imp
    assert "compress/mode=0" in imp
    assert res["pixelart_filter_set"] is True
    pg = open(os.path.join(proj, "project.godot"), encoding="utf-8").read()
    assert "rendering/textures/canvas_textures/default_texture_filter=0" in pg


def test_edge_music_loop_on(tmp_path):
    proj = _godot_proj(tmp_path)
    wav = tmp_path / "theme.wav"
    wav.write_bytes(b"RIFF....WAVE")   # contenido falso: el .import no decodifica aqui
    res = comfyui_export_asset_to_godot(str(wav), "music", proj, reimport=False)
    assert res["ok"] is True
    assert res["dest_res_path"] == "res://assets/audio/music/theme.wav"
    imp = open(res["import_path"], encoding="utf-8").read()
    assert 'importer="wav"' in imp
    assert "edit/loop_mode=1" in imp        # musica -> loop ON


def test_edge_sfx_loop_off(tmp_path):
    proj = _godot_proj(tmp_path)
    wav = tmp_path / "step.wav"
    wav.write_bytes(b"RIFF....WAVE")
    res = comfyui_export_asset_to_godot(str(wav), "sfx", proj, reimport=False)
    assert res["ok"] is True
    imp = open(res["import_path"], encoding="utf-8").read()
    assert "edit/loop_mode=0" in imp        # sfx -> loop OFF


def test_edge_model_glb_scene(tmp_path):
    proj = _godot_proj(tmp_path)
    glb = tmp_path / "robot_00001_.glb"
    glb.write_bytes(b"glTF....")
    res = comfyui_export_asset_to_godot(str(glb), "model", proj, reimport=False)
    assert res["ok"] is True
    assert res["dest_res_path"] == "res://assets/models/robot.glb"
    imp = open(res["import_path"], encoding="utf-8").read()
    assert 'importer="scene"' in imp


def test_edge_tileset_warns(tmp_path):
    proj = _godot_proj(tmp_path)
    res = comfyui_export_asset_to_godot(_png(tmp_path, "tiles_00001_.png"), "tileset", proj,
                                        reimport=False)
    assert res["ok"] is True
    assert any("TileSet" in w for w in res["warnings"])


def test_idempotent_preserves_uid(tmp_path):
    proj = _godot_proj(tmp_path)
    asset = _png(tmp_path)
    r1 = comfyui_export_asset_to_godot(asset, "sprite", proj, reimport=False)
    # inyecta un uid en el .import como si Godot ya lo hubiera asignado
    imp_path = r1["import_path"]
    txt = open(imp_path, encoding="utf-8").read().replace(
        'importer="texture"\n', 'importer="texture"\nuid="uid://abc123xyz"\n'
    )
    open(imp_path, "w", encoding="utf-8").write(txt)
    r2 = comfyui_export_asset_to_godot(asset, "sprite", proj, reimport=False)
    assert 'uid="uid://abc123xyz"' in open(r2["import_path"], encoding="utf-8").read()


def test_error_missing_asset(tmp_path):
    proj = _godot_proj(tmp_path)
    res = comfyui_export_asset_to_godot(str(tmp_path / "nope.png"), "sprite", proj)
    assert res["ok"] is False
    assert "no existe" in res["error"]


def test_error_bad_kind(tmp_path):
    proj = _godot_proj(tmp_path)
    res = comfyui_export_asset_to_godot(_png(tmp_path), "hologram", proj, reimport=False)
    assert res["ok"] is False


def test_error_not_a_godot_project(tmp_path):
    asset = _png(tmp_path)
    res = comfyui_export_asset_to_godot(asset, "sprite", str(tmp_path / "empty"))
    assert res["ok"] is False
    assert "project.godot" in res["error"]


def test_godot_cli_absent_leaves_import(tmp_path):
    proj = _godot_proj(tmp_path)
    asset = _png(tmp_path)
    res = comfyui_export_asset_to_godot(asset, "sprite", proj, reimport=True,
                                        godot_bin="/no/such/godot")
    assert res["ok"] is True
    assert res["import_written"] is True
    assert res["reimported"] is False
    assert any("Godot CLI no encontrado" in w for w in res["warnings"])
