import asyncio
import sys
from uuid import UUID

from src.config import get_settings
from src.core.database import async_session_factory
from src.domain.project_auth.cloud_projection import build_project_projections
from src.domain.project_auth.cloud_projection_source import load_project_snapshot
from src.domain.project_auth.membership_projection_sync import sync_project_projections
from src.integrations.auth_projection_writer import CloudAuthProjectionWriter

P = UUID("b3241454-baab-4bfa-8862-6bfdd3d76898")
APPLY = "--apply" in sys.argv


async def main():
    s = get_settings()

    async with async_session_factory() as db:
        snap = await load_project_snapshot(db, P)

        for p in build_project_projections(snap):
            print(
                p.email,
                p.status,
                "cloud_id=",
                p.cloud_app_user_id,
                "roles=",
                p.project_roles,
                "permissions=",
                len(p.project_permissions),
                "version=",
                p.authorization_version,
            )

        if not APPLY:
            print("DRY RUN: nothing sent. Re-run with --apply to sync.")
            return

        writer = CloudAuthProjectionWriter(
            s.cloud_control_api_url,
            s.cloud_auth_projection_secret,
        )

        outcomes = await sync_project_projections(
            db,
            P,
            writer,
        )

        await db.commit()

        for o in outcomes:
            print(
                o.email,
                o.status,
                o.code or "",
            )


asyncio.run(main())
