"""Seed demo tenants and users for local development."""
import asyncio
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession

from ams.core.config import settings

DATABASE_URL = settings.DATABASE_URL

# Fixed tenant ids so a fresh seed is reproducible: the test suite and the
# dedicated government DB both hardcode these (conftest seeded_user =
# e622f098…, gov schema tenant_93217557…). A random uuid4 per seed would only
# match by luck on a never-reset DB and break every isolated/CI run.
TENANTS = [
    {"id": "e622f098-7f90-41f3-b802-8db9431535ce", "slug": "demo-enterprise", "plan": "enterprise", "status": "active"},
    {"id": "93217557-3c02-4c05-9fd4-3e01df087352", "slug": "demo-government", "plan": "government", "status": "active"},
]


async def provision_tenant(session: AsyncSession, tenant_id: str):
    # Only the schema — Alembic (migration 0001) owns creating `users` and
    # every other table. A manually pre-created `users` table here collides
    # with migration 0001's CREATE TABLE, which Alembic's env.py then treats
    # as "already migrated" and skips — silently leaving the whole schema
    # stuck with no tables beyond this placeholder, forever.
    schema = f"tenant_{tenant_id.replace('-', '_')}"
    await session.execute(text(f"CREATE SCHEMA IF NOT EXISTS {schema}"))
    print(f"  Schema {schema} provisioned")


async def seed():
    engine = create_async_engine(DATABASE_URL, echo=False)
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with Session() as session:
        for tenant_data in TENANTS:
            await session.execute(text("""
                INSERT INTO public.tenants (id, slug, plan, status)
                VALUES (:id, :slug, :plan, :status)
                ON CONFLICT (slug) DO NOTHING
            """), tenant_data)

            result = await session.execute(
                text("SELECT id FROM public.tenants WHERE slug = :slug"),
                {"slug": tenant_data["slug"]}
            )
            row = result.fetchone()
            if row:
                await provision_tenant(session, str(row[0]))

        # Commit tenant rows/schemas now — independent of whether master-data
        # seeding below succeeds. Without this, a mid-loop failure (e.g. a
        # schema not yet migrated) rolls back the tenant row too, so the next
        # run recreates it with a fresh random UUID instead of resuming.
        await session.commit()

    # Register the same tenants in the ams_master registry (a SEPARATE db) —
    # this is the tenant-resolution middleware's source of truth (it maps
    # X-Tenant-Slug -> tenant_id via ams_master.tenants, NOT public.tenants).
    # init.sql creates the ams_master.tenants table but leaves it empty, so a
    # fresh env can't resolve any slug and every login 401s. Same fixed ids as
    # above keep both registries in sync. Idempotent (ON CONFLICT DO NOTHING).
    master_engine = create_async_engine(settings.MASTER_DATABASE_URL, echo=False)
    async with master_engine.begin() as mconn:
        for t in TENANTS:
            await mconn.execute(text("""
                INSERT INTO tenants (id, name, slug, plan, status)
                VALUES (:id, :name, :slug, :plan, :status)
                ON CONFLICT (slug) DO NOTHING
            """), {**t, "name": t["slug"].replace("-", " ").title()})
    await master_engine.dispose()
    print("  ams_master registry synced")

    async with Session() as session:

        # Seed asset masters into each tenant schema
        for tenant_data in TENANTS:
            result = await session.execute(
                text("SELECT id FROM public.tenants WHERE slug = :slug"),
                {"slug": tenant_data["slug"]}
            )
            row = result.fetchone()
            if row:
                tenant_id = str(row[0])
                schema = f"tenant_{tenant_id.replace('-', '_')}"
                await session.execute(text(f"SET search_path TO {schema}, public"))
                from ams.data.seed_tenant_masters import seed_tenant_masters
                await seed_tenant_masters(session, label=tenant_data["slug"])

        await session.commit()
        print("Seed complete.")

    await engine.dispose()


if __name__ == "__main__":
    asyncio.run(seed())


