import os
import tempfile
from pathlib import Path

import pytest

os.environ["SECRET_KEY"] = "test-secret-key-only-for-tests-not-secure"
os.environ["ADMIN_USER"] = "testadmin"
os.environ["ADMIN_PASS"] = "testpass"
os.environ["TOKEN_EXPIRY_HOURS"] = "24"
os.environ["BASE_URL"] = "http://testserver"

_tmp = Path(tempfile.mkdtemp(prefix="taller-wox-test-"))
os.environ["DB_PATH"] = str(_tmp / "test_leads.db")
os.environ["MATERIAL_DIR"] = str(_tmp / "material")
os.environ["REPORTS_OUTPUT_DIR"] = str(_tmp / "reports_output")
(_tmp / "material").mkdir(parents=True, exist_ok=True)
(_tmp / "reports_output").mkdir(parents=True, exist_ok=True)


@pytest.fixture
def client():
    from fastapi.testclient import TestClient

    from app.main import app
    return TestClient(app)


@pytest.fixture(autouse=True)
def _init_db_each_test(tmp_path, monkeypatch):
    db_file = tmp_path / "test.db"
    monkeypatch.setenv("DB_PATH", str(db_file))
    from app import config
    config.get_settings.cache_clear()
    from app.db import init_db
    init_db()
    yield
    config.get_settings.cache_clear()
