from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

API_DIR = Path(__file__).resolve().parents[1]
os.chdir(API_DIR)
sys.path.insert(0, str(API_DIR))

db_file = API_DIR / ".e2e.sqlite"
if db_file.exists():
    db_file.unlink()

os.environ["DATABASE_URL"] = f"sqlite+pysqlite:///{db_file.as_posix()}"
os.environ["EMAIL_DELIVERY_MODE"] = "memory"
os.environ["STORAGE_MODE"] = "memory"
os.environ["ENABLE_RATE_LIMIT"] = "false"
os.environ["ENABLE_TEST_ROUTES"] = "true"
web_port = os.environ.get("E2E_WEB_PORT", "5175")
os.environ["CORS_ORIGINS"] = f'["http://127.0.0.1:{web_port}","http://localhost:{web_port}"]'

port = os.environ.get("E2E_API_PORT", "8001")

subprocess.run(
    [sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", port],
    cwd=API_DIR,
    check=True,
)
