"""Run Alembic migrations for all tenant schemas in public.organizations.

Usage:
    venv/bin/python scripts/run_tenant_migrations.py [--schema tenant_xyz]

Without --schema: migrates public schema first, then all tenant schemas.
With --schema: migrates only the specified tenant schema.
"""
import argparse
import os
import sys

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

from sqlalchemy import text, create_engine
from alembic.config import Config as AlembicConfig
from alembic import command as alembic_command

from supporthub.app.config import Config

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ALEMBIC_INI = os.path.join(PROJECT_ROOT, "alembic.ini")


def _run(schema=None):
    """Run alembic upgrade head for a given schema (None = public schema)."""
    cfg = AlembicConfig(ALEMBIC_INI)
    if schema:
        cfg.attributes["tenant_schema"] = schema
    alembic_command.upgrade(cfg, "head")


def get_all_schemas():
    engine = create_engine(Config.database_url())
    with engine.connect() as conn:
        rows = conn.execute(
            text("SELECT schema_name FROM public.organizations ORDER BY id")
        ).fetchall()
    return [r[0] for r in rows]


def main():
    parser = argparse.ArgumentParser(description="Run tenant Alembic migrations")
    parser.add_argument("--schema", help="Migrate only this schema (e.g. tenant_abc123)")
    args = parser.parse_args()

    if args.schema:
        print(f"Migrating schema: {args.schema}...")
        _run(schema=args.schema)
        print(f"  {args.schema} done.")
    else:
        schemas = get_all_schemas()
        print(f"Found {len(schemas)} tenant schema(s): {schemas}")

        print("Migrating public schema...")
        _run(schema=None)
        print("  public schema done.")

        for schema in schemas:
            print(f"Migrating schema: {schema}...")
            _run(schema=schema)
            print(f"  {schema} done.")

    print("All migrations complete.")


if __name__ == "__main__":
    main()
