"""Ensure a platform admin user exists (idempotent). Uses DATABASE_URL from settings / .env."""

from __future__ import annotations

import argparse
import asyncio
import sys

from sqlalchemy import select

from aif_platform.server.auth.password import hash_password
from aif_platform.server.db.connection import async_session_maker, init_db
from aif_platform.server.models.persistence import (
    PlatformOrganization,
    PlatformOrgMembership,
    PlatformUser,
)
def _norm_email(email: str) -> str:
    return email.strip().lower()


async def run(
    *,
    email: str,
    password: str,
    org_name: str,
) -> int:
    await init_db()
    norm = _norm_email(email)
    async with async_session_maker() as db:
        user = (
            await db.execute(select(PlatformUser).where(PlatformUser.email == norm))
        ).scalar_one_or_none()
        if user:
            user.is_platform_admin = True
            user.password_hash = hash_password(password)
            await db.commit()
            print(f"Updated existing user {norm!r}: platform admin + password reset.", file=sys.stderr)
            return 0

        user = PlatformUser(
            email=norm,
            password_hash=hash_password(password),
            is_platform_admin=True,
        )
        db.add(user)
        await db.flush()

        org = PlatformOrganization(name=org_name.strip() or "Admin organization")
        db.add(org)
        await db.flush()

        db.add(
            PlatformOrgMembership(
                user_id=user.id,
                org_id=org.id,
                role="owner",
            )
        )
        await db.commit()
        print(f"Created platform admin {norm!r} with organization {org.name!r}.", file=sys.stderr)
        return 0


def main() -> None:
    p = argparse.ArgumentParser(description="Bootstrap or upgrade a platform admin user.")
    p.add_argument("--email", default="admin@langxai.com", help="Login email (stored lowercased)")
    p.add_argument("--password", default="admin", help="Plain password (bcrypt hashed in DB)")
    p.add_argument(
        "--org-name",
        default="Langxai Admin",
        help="Organization name when creating a new user",
    )
    args = p.parse_args()
    raise SystemExit(asyncio.run(run(email=args.email, password=args.password, org_name=args.org_name)))


if __name__ == "__main__":
    main()
