"""Database setup (SQLAlchemy). The database is OPTIONAL for this app.

Nothing here connects at import time, so the app boots and serves /health
with no database at all. DATABASE_URL is provided automatically when the
app has a database: locally by `ghosty dev`, in production by the
Ghosty platform.
"""

import os

from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker

# Local development reads backend/.env.local (gitignored). In production
# the platform injects env vars directly; this is a no-op there.
load_dotenv(".env.local")

DATABASE_URL = os.environ.get("DATABASE_URL", "")

engine = create_engine(DATABASE_URL) if DATABASE_URL else None
SessionLocal = sessionmaker(bind=engine) if engine else None


class Base(DeclarativeBase):
    """Base class for all models in src/models/."""


def get_db():
    """FastAPI dependency that yields a database session.

    Usage:
        from fastapi import Depends
        from sqlalchemy.orm import Session
        from src.db import get_db

        @router.get("/")
        def list_items(db: Session = Depends(get_db)):
            ...
    """
    if SessionLocal is None:
        raise RuntimeError(
            "DATABASE_URL is not set. This app does not have a database yet — "
            "enable one in app.config.json and re-provision, or run `ghosty dev` "
            "to get local dev credentials."
        )
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
