import os
import subprocess
import sys
import tempfile
from pathlib import Path

# needs to be on sys.path before any layer imports, and before DATABASE_URL is read
_BACKEND_DIR = Path(__file__).resolve().parent.parent
if str(_BACKEND_DIR) not in sys.path:
    sys.path.insert(0, str(_BACKEND_DIR))

_TMPDIR = tempfile.mkdtemp(prefix="routerisk_test_")
_FIXTURE_DB = Path(_TMPDIR) / "fixture.db"
_OUTPUT_DIR = Path(_TMPDIR) / "frontend_data"
_OUTPUT_DIR.mkdir()

subprocess.run(
    [sys.executable, str(Path(__file__).parent / "fixtures" / "make_fixture_db.py"), str(_FIXTURE_DB)],
    check=True,
)

os.environ["DATABASE_URL"] = f"sqlite:///{_FIXTURE_DB}"
os.environ["MIN_ROUTE_FLIGHTS"]   = "5"
os.environ["MIN_CARRIER_FLIGHTS"] = "3"
os.environ["MIN_CHAIN_OBS"]       = "3"

# import after env var is set so the engine gets the right URL
import core.utils  # noqa: E402

core.utils.get_output_path = lambda filename: _OUTPUT_DIR / filename
