"""Bootstrap the public schema for a fresh ModuleDesk PostgreSQL install.

Creates public.organizations, public.users, public.plans, public.audit_log
and seeds the owner (internal) org + platform_admin user.

Usage:
    venv/bin/python scripts/bootstrap_public_schema.py

Run once after the PostgreSQL database is created and before running
tenant migrations.
"""

import sys
import os
import datetime as dt

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from supporthub.app.db import engine, session_scope
from supporthub.app.public_models import PublicBase, Organization, User, Plan

OWNER_EMAIL = "admin@local.test"
OWNER_HASH = "$2b$12$ZmmONDck4pEpkwCaQ4DaNuUk1zcJm86Nv3rLZDlc5TCDHsVXSDGpK"
OWNER_SCHEMA = "tenant_internal"


def seed_plans(session) -> None:
    plan_defs = [
        {
            "name": "internal",
            "price_per_module_cents": 0,
            "ai_credits_per_month": None,
            "module_limit": None,
            "template_limit": None,
            "features_json": '{"all": true}',
        },
        {
            "name": "free",
            "price_per_module_cents": 0,
            "ai_credits_per_month": 20,
            "module_limit": 2,
            "template_limit": 5,
            "features_json": "{}",
        },
        {
            "name": "basic",
            "price_per_module_cents": 500,
            "ai_credits_per_month": 200,
            "module_limit": None,
            "template_limit": None,
            "features_json": "{}",
        },
        {
            "name": "pro",
            "price_per_module_cents": 1000,
            "ai_credits_per_month": None,
            "module_limit": None,
            "template_limit": None,
            "features_json": '{"byok": true}',
        },
    ]
    for p in plan_defs:
        existing = session.query(Plan).filter_by(name=p["name"]).one_or_none()
        if not existing:
            session.add(Plan(**p))
            print(f"  plan '{p['name']}' created")
        else:
            print(f"  plan '{p['name']}' already exists, skipping")


def seed_owner_org(session) -> Organization:
    existing = session.query(Organization).filter_by(slug="internal").one_or_none()
    if existing:
        print(f"  org 'internal' already exists (id={existing.id}), skipping")
        return existing

    org = Organization(
        name="ModuleDesk Internal",
        slug="internal",
        schema_name=OWNER_SCHEMA,
        plan="internal",
        email_verified=True,
        onboarding_complete=True,
        created_at=dt.datetime.utcnow(),
    )
    session.add(org)
    session.flush()
    print(f"  org 'internal' created (id={org.id}, schema={org.schema_name})")
    return org


def seed_owner_user(session, org: Organization) -> None:
    existing = session.query(User).filter_by(email=OWNER_EMAIL).one_or_none()
    if existing:
        print(f"  user '{OWNER_EMAIL}' already exists (id={existing.id}), skipping")
        return

    user = User(
        org_id=org.id,
        email=OWNER_EMAIL,
        password_hash=OWNER_HASH,
        role="platform_admin",
        email_verified=True,
        created_at=dt.datetime.utcnow(),
    )
    session.add(user)
    print(f"  user '{OWNER_EMAIL}' created (role=platform_admin)")


def main() -> None:
    print("Step 1: Creating public schema tables...")
    PublicBase.metadata.create_all(engine)
    print("  Tables created (or already exist)")

    print("Step 2: Seeding plans...")
    with session_scope() as session:
        seed_plans(session)

    print("Step 3: Creating internal org...")
    with session_scope() as session:
        org = seed_owner_org(session)
        session.flush()
        org_id = org.id
        org_schema = org.schema_name

    print("Step 4: Creating platform_admin user...")
    with session_scope() as session:
        org = session.query(Organization).filter_by(id=org_id).one()
        seed_owner_user(session, org)

    print(f"\nBootstrap complete.")
    print(f"  Org: 'internal' (id={org_id}, schema={org_schema})")
    print(f"  User: {OWNER_EMAIL} (role=platform_admin, plan=internal)")
    print(f"\nNext: run tenant migrations for schema '{org_schema}':")
    print(f"  venv/bin/python scripts/run_tenant_migrations.py --schema {org_schema}")


if __name__ == "__main__":
    main()
