"""One-off: reset a tenant's super_admin password to a known value.
Usage: docker compose exec api python reset_super_admin_password.py <tenant_slug> <new_password>
"""
import asyncio
import sys

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

from ams.core.config import settings
from ams.core.security import hash_password


async def main() -> None:
    slug, new_password = sys.argv[1], sys.argv[2]
    engine = create_async_engine(settings.DATABASE_URL, echo=False)
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    async with Session() as session:
        tenant_id = (await session.execute(
            text("SELECT id::text FROM public.tenants WHERE slug = :slug"), {"slug": slug}
        )).scalar_one()
        schema = f"tenant_{tenant_id.replace('-', '_')}"
        await session.execute(text(f"SET search_path TO {schema}, public"))
        existing = (await session.execute(
            text(f"SELECT email FROM {schema}.users WHERE role = 'super_admin'")
        )).scalars().all()
        if len(existing) != 1:
            print(f"Aborting — expected exactly 1 super_admin in '{slug}', found {len(existing)}: {existing}")
            return
        result = await session.execute(
            text(f"UPDATE {schema}.users SET password_hash = :ph WHERE role = 'super_admin' RETURNING email"),
            {"ph": hash_password(new_password)},
        )
        emails = [row[0] for row in result.fetchall()]
        await session.commit()
        print(f"Reset password for {emails} in tenant '{slug}'")


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