"""Phase-1: app startup must not initialize DeepFace/TF; lazy load is thread-safe."""

from __future__ import annotations

import importlib.machinery
import sys
import threading
import types
from concurrent.futures import ThreadPoolExecutor

import pytest
from fastapi.testclient import TestClient

from app.config import Settings, get_settings
from app.main import app
from app.services.face.deps import clear_face_stack_cache, probe_face_stack
from app.services.face.engine import get_face_engine, set_face_engine_override
from app.services.face.lazy_deepface import (
    deepface_import_attempts,
    get_deepface,
    is_deepface_loaded,
    reset_deepface_lazy_state_for_tests,
)


@pytest.fixture(autouse=True)
def _reset_lazy():
    reset_deepface_lazy_state_for_tests()
    set_face_engine_override(None)
    clear_face_stack_cache()
    # Do not leave a ModuleType stub in sys.modules — find_spec("deepface")
    # raises ValueError when __spec__ is None (breaks later stub smoke tests).
    previous = sys.modules.get("deepface")
    yield
    reset_deepface_lazy_state_for_tests()
    set_face_engine_override(None)
    if previous is None:
        sys.modules.pop("deepface", None)
    else:
        sys.modules["deepface"] = previous
    clear_face_stack_cache()


def _install_fake_deepface() -> None:
    mod = types.ModuleType("deepface")
    # find_spec requires a non-None __spec__ when the name is already in sys.modules
    mod.__spec__ = importlib.machinery.ModuleSpec("deepface", loader=None)

    class FakeDeepFace:
        pass

    mod.DeepFace = FakeDeepFace  # type: ignore[attr-defined]
    sys.modules["deepface"] = mod


def test_health_and_ready_do_not_init_deepface() -> None:
    assert is_deepface_loaded() is False
    assert deepface_import_attempts() == 0
    client = TestClient(app)
    assert client.get("/api/v1/health").status_code == 200
    assert client.get("/api/v1/ready").status_code == 200
    assert is_deepface_loaded() is False
    assert deepface_import_attempts() == 0


def test_non_cv_endpoint_does_not_init_deepface() -> None:
    client = TestClient(app)
    token = get_settings().internal_api_token
    res = client.get("/api/v1/personas", headers={"X-Internal-Token": token})
    assert res.status_code == 200
    assert is_deepface_loaded() is False
    assert deepface_import_attempts() == 0


def test_get_face_engine_does_not_import_deepface() -> None:
    engine = get_face_engine()
    assert engine.name == "deepface"
    assert is_deepface_loaded() is False
    assert deepface_import_attempts() == 0


def test_get_deepface_imports_once_and_reuses() -> None:
    _install_fake_deepface()
    reset_deepface_lazy_state_for_tests()
    a = get_deepface()
    b = get_deepface()
    assert a is b
    assert is_deepface_loaded() is True
    assert deepface_import_attempts() == 1


def test_concurrent_get_deepface_single_import() -> None:
    _install_fake_deepface()
    reset_deepface_lazy_state_for_tests()
    barrier = threading.Barrier(8)
    results: list[object] = []

    def worker() -> None:
        barrier.wait(timeout=5)
        results.append(get_deepface())

    with ThreadPoolExecutor(max_workers=8) as pool:
        futs = [pool.submit(worker) for _ in range(8)]
        for f in futs:
            f.result(timeout=10)

    assert len(results) == 8
    assert all(r is results[0] for r in results)
    assert deepface_import_attempts() == 1


def test_video_max_frames_default_is_phase1() -> None:
    assert Settings.model_fields["video_max_frames"].default == 16


def test_probe_face_stack_survives_broken_deepface_spec() -> None:
    """Regression: ModuleType stub without __spec__ must not crash deps probe."""
    clear_face_stack_cache()
    broken = types.ModuleType("deepface")
    assert broken.__spec__ is None
    sys.modules["deepface"] = broken
    try:
        status = probe_face_stack()
        # Should not raise; module is present in sys.modules
        assert status.deepface is True
    finally:
        sys.modules.pop("deepface", None)
        clear_face_stack_cache()
