"""One-off backfill: adds the new AI_ENABLED/AI_PROVIDER/AI_MODEL/AI_API_KEY
rows (added to ams/data/seed_system_config.py's SYSTEM_PARAMS) to every
EXISTING tenant schema. seed_system_config() only runs automatically for
brand-new tenants (seed_tenant_masters.py) — existing tenants need this
one-off pass. Reuses the real seed_system_config() function (idempotent,
ON CONFLICT (key) DO NOTHING) rather than re-implementing the insert.

Usage: docker compose exec api python backfill_ai_config.py
"""
import asyncio

from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from ams.core.config import settings
from ams.data.seed_system_config import seed_system_config


async def main() -> None:
    engine = create_async_engine(settings.DATABASE_URL, echo=False)
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with Session() as session:
        tenants = (await session.execute(
            text("SELECT id::text AS id, slug FROM public.tenants WHERE status != 'archived'")
        )).fetchall()

    for tenant in tenants:
        schema = f"tenant_{tenant.id.replace('-', '_')}"
        async with Session() as session:
            await session.execute(text(f"SET search_path TO {schema}, public"))
            try:
                await seed_system_config(session)
                await session.commit()
                print(f"  backfilled: {tenant.slug}")
            except Exception as exc:
                print(f"  SKIPPED {tenant.slug}: {exc}")
                await session.rollback()

    await engine.dispose()
    print(f"Done — {len(tenants)} tenant(s) processed.")


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