"""Tests para hf_snapshot_download — mockear snapshot_download y verificar args."""

import sys
import types

sys.path.insert(0, "python/functions/ml")

import pytest

# Saltar si huggingface_hub no esta disponible Y no podemos mockearlo
# Usamos un mock inline para no requerir la lib real.
# Si la lib esta disponible, monkeypatch la reemplaza. Si no, la inyectamos manualmente.


def _inject_fake_hf_hub(monkeypatch, capture: list):
    """Inyecta un modulo huggingface_hub falso con snapshot_download que captura kwargs."""

    def fake_snapshot_download(**kwargs):
        capture.append(kwargs)
        return "/tmp/fake_snapshot"

    fake_module = types.ModuleType("huggingface_hub")
    fake_module.snapshot_download = fake_snapshot_download
    monkeypatch.setitem(sys.modules, "huggingface_hub", fake_module)


def test_args_minimos_repo_id(monkeypatch):
    """repo_id se pasa correctamente a snapshot_download"""
    capture = []
    _inject_fake_hf_hub(monkeypatch, capture)

    from hf_snapshot_download import hf_snapshot_download
    result = hf_snapshot_download("runwayml/stable-diffusion-v1-5")

    assert len(capture) == 1
    assert capture[0]["repo_id"] == "runwayml/stable-diffusion-v1-5"
    assert result == "/tmp/fake_snapshot"


def test_retorna_string(monkeypatch):
    """hf_snapshot_download retorna un string (la ruta local)"""
    capture = []
    _inject_fake_hf_hub(monkeypatch, capture)

    from hf_snapshot_download import hf_snapshot_download
    result = hf_snapshot_download("some/repo")

    assert isinstance(result, str)


def test_allow_patterns_se_pasa(monkeypatch):
    """allow_patterns se incluye en los kwargs si se especifica"""
    capture = []
    _inject_fake_hf_hub(monkeypatch, capture)

    from hf_snapshot_download import hf_snapshot_download
    hf_snapshot_download("some/repo", allow_patterns=["*.safetensors", "*.json"])

    assert "allow_patterns" in capture[0]
    assert capture[0]["allow_patterns"] == ["*.safetensors", "*.json"]


def test_ignore_patterns_se_pasa(monkeypatch):
    """ignore_patterns se incluye en los kwargs si se especifica"""
    capture = []
    _inject_fake_hf_hub(monkeypatch, capture)

    from hf_snapshot_download import hf_snapshot_download
    hf_snapshot_download("some/repo", ignore_patterns=["*.bin", "flax_*"])

    assert "ignore_patterns" in capture[0]
    assert capture[0]["ignore_patterns"] == ["*.bin", "flax_*"]


def test_local_dir_se_pasa(monkeypatch):
    """local_dir se incluye en los kwargs si se especifica"""
    capture = []
    _inject_fake_hf_hub(monkeypatch, capture)

    from hf_snapshot_download import hf_snapshot_download
    hf_snapshot_download("some/repo", local_dir="/models/sd15")

    assert "local_dir" in capture[0]
    assert capture[0]["local_dir"] == "/models/sd15"


def test_token_se_pasa(monkeypatch):
    """token se incluye en los kwargs si se especifica"""
    capture = []
    _inject_fake_hf_hub(monkeypatch, capture)

    from hf_snapshot_download import hf_snapshot_download
    hf_snapshot_download("private/model", token="hf_mytoken123")

    assert "token" in capture[0]
    assert capture[0]["token"] == "hf_mytoken123"


def test_none_args_no_se_pasan(monkeypatch):
    """args opcionales None no se incluyen en kwargs (no contaminar snapshot_download)"""
    capture = []
    _inject_fake_hf_hub(monkeypatch, capture)

    from hf_snapshot_download import hf_snapshot_download
    hf_snapshot_download("some/repo")

    kwargs = capture[0]
    # Solo repo_id debe estar presente — los None no se incluyen
    assert "allow_patterns" not in kwargs
    assert "ignore_patterns" not in kwargs
    assert "local_dir" not in kwargs
    assert "token" not in kwargs


def test_import_error_sin_huggingface_hub(monkeypatch):
    """ImportError descriptivo si huggingface_hub no esta instalado"""
    import importlib

    # Inyectar None en sys.modules para simular libreria no instalada
    monkeypatch.setitem(sys.modules, "huggingface_hub", None)

    # Recargar el modulo para que el try/except del top-level vea el None
    import hf_snapshot_download as _mod
    importlib.reload(_mod)

    from hf_snapshot_download import hf_snapshot_download
    with pytest.raises(ImportError, match="huggingface_hub"):
        hf_snapshot_download("any/repo")
