from __future__ import annotations

import os
import sys
from pathlib import Path

APP_ROOT = Path(__file__).resolve().parent


def _find_virtualenv_python() -> Path | None:
    candidates = [
        APP_ROOT / "venv" / "bin" / "python",
        Path.home() / "guardiansteps_venv" / "bin" / "python",
        APP_ROOT / "bin" / "python",
    ]
    cloudlinux_root = Path.home() / "virtualenv" / APP_ROOT.name
    if cloudlinux_root.exists():
        candidates.extend(sorted(cloudlinux_root.glob("*/bin/python"), reverse=True))
    for candidate in candidates:
        if candidate.exists():
            return candidate.resolve()
    return None


virtualenv_python = _find_virtualenv_python()
if virtualenv_python is not None and Path(sys.executable).resolve() != virtualenv_python:
    os.execl(str(virtualenv_python), str(virtualenv_python), *sys.argv)


def _load_env(path: Path) -> None:
    if not path.exists():
        return
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        if key:
            os.environ.setdefault(key, value)


_load_env(APP_ROOT / ".env")

DATA_DIR = APP_ROOT / "data"
DATA_DIR.mkdir(parents=True, exist_ok=True)

os.environ.setdefault("APP_NAME", "GuardianSteps API")
os.environ.setdefault("ENVIRONMENT", "production")
os.environ.setdefault("DATABASE_URL", f"sqlite:///{DATA_DIR / 'guardiansteps.db'}")
os.environ.setdefault("ACCESS_TOKEN_HOURS", "12")
os.environ.setdefault("PAIRING_CODE_MINUTES", "15")
os.environ.setdefault("PORTAL_ORIGIN", "https://child.selzo.online")
os.environ.setdefault("AUTO_SEED", "false")
os.environ.setdefault("ENABLE_DOCS", "false")

jwt_secret = os.environ.get("JWT_SECRET", "")
if len(jwt_secret) < 32 or jwt_secret.startswith("CHANGE_ME"):
    raise RuntimeError(
        "Set a persistent JWT_SECRET of at least 32 characters in "
        f"{APP_ROOT / '.env'} before starting GuardianSteps."
    )

server_dir = APP_ROOT / "server"
if str(server_dir) not in sys.path:
    sys.path.insert(0, str(server_dir))

from a2wsgi import ASGIMiddleware  # noqa: E402
from app.config import settings  # noqa: E402
from app.database import Base, SessionLocal, engine  # noqa: E402
from app.main import app as asgi_app  # noqa: E402
from app.seed import seed_demo  # noqa: E402

# Passenger exposes WSGI rather than ASGI. Initialize the database explicitly,
# because FastAPI lifespan events are not invoked by the WSGI compatibility layer.
Base.metadata.create_all(bind=engine)
if settings.auto_seed:
    with SessionLocal() as db:
        seed_demo(db)

application = ASGIMiddleware(asgi_app, wait_time=30.0)
