"""Seed the founding invites. Idempotent — runs on every container start.

dailysplice is invite-only (plan D3). The invite table is the allowlist, and
these are the rows it starts with. Everyone else who signs in with a BW account
gets `role='none'` and the "not invited" screen.

Seeding is INSERT-if-absent only: an existing invite row is never modified, so
changing someone's role in the database (or later, in the admin UI) is not
reverted on the next deploy. To change a founding invite, change the database —
editing this file only affects a fresh install.

Note that an invite governs *admission at first sign-in*. Once a user has been
admitted, their role lives on their `users` row; removing an invite here does
not lock them out (see services/identity.py).
"""

from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from sqlalchemy import func, select  # noqa: E402

from app.db import get_session_factory  # noqa: E402
from app.models.identity import Invite  # noqa: E402
from app.services.roles import ROLE_SUPERADMIN, ROLE_USER  # noqa: E402

# (email, role, note). The founding roster.
FOUNDING_INVITES: list[tuple[str, str, str]] = [
    ("rian@rian.ca", ROLE_SUPERADMIN, "Owner and builder."),
    ("jsbowden58@gmail.com", ROLE_USER, "First invited user."),
]


def main() -> int:
    added = 0
    with get_session_factory()() as db:
        for email, role, note in FOUNDING_INVITES:
            email = email.strip().lower()
            existing = db.scalar(
                select(Invite).where(func.lower(Invite.email) == email)
            )
            if existing is not None:
                continue
            db.add(Invite(email=email, role=role, note=note))
            added += 1
        db.commit()
    present = len(FOUNDING_INVITES) - added
    print(f"seed: {added} invite(s) added, {present} already present")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
