#!/usr/bin/env python
"""Manually trigger dispatcher Worker deployment outside of the worker process.

The dispatcher is normally deployed automatically every time the arq worker
starts (src/workers/main.py startup hook).  Run this script only if you need
to deploy/update the dispatcher without restarting the worker.

Usage:
  python -m scripts.deploy_dispatcher
  python -m scripts.deploy_dispatcher --dry-run
"""
from __future__ import annotations

import argparse
import asyncio
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.core.orm_import import import_all_orm_models
import_all_orm_models()


async def main(dry_run: bool = False) -> int:
    from src.config import get_settings
    from src.domain.hosting.routing_plane import CloudflareRoutingProvider

    s = get_settings()

    if not s.cloudflare_api_token or not s.cloudflare_account_id:
        print("ERROR: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID must be set in .env", file=sys.stderr)
        return 1

    apex = (s.hosting_public_apex or "sites.p2hs.com").strip()
    ns_prod = (s.cloudflare_w4p_namespace_production or s.cloudflare_w4p_namespace or "p2hs-production").strip()
    ns_prev = (s.cloudflare_w4p_namespace_preview or s.cloudflare_w4p_namespace or "p2hs-preview").strip()
    zone_id = (getattr(s, "cloudflare_zone_id", None) or "").strip()

    print(f"Account  : {s.cloudflare_account_id}")
    print(f"Apex     : {apex}")
    print(f"NS prod  : {ns_prod}")
    print(f"NS prev  : {ns_prev}")
    print(f"Zone ID  : {zone_id or '(not set — route registration skipped)'}")
    print(f"KV ID    : {s.cloudflare_dispatch_kv_namespace_id or '(not set)'}")
    print()

    if dry_run:
        provider = CloudflareRoutingProvider(s)
        print("[dry-run] Dispatcher source preview:")
        print("-" * 60)
        print(provider._dispatcher_source(apex)[:600])  # noqa: SLF001
        print("[dry-run] No API calls made.")
        return 0

    print("Deploying dispatcher Worker ...")
    result = await CloudflareRoutingProvider(s).deploy_dispatcher(apex)
    print(f"  script : {result.get('script_name')}")
    print(f"  route  : {result.get('route', 'skipped (no CLOUDFLARE_ZONE_ID)')}")
    print()
    print("Done. The worker startup hook runs this automatically on every restart.")
    return 0


def cli() -> int:
    p = argparse.ArgumentParser(description="Deploy P2HS dispatcher Worker (normally auto-run on worker startup)")
    p.add_argument("--dry-run", action="store_true", help="Print config without making API calls")
    args = p.parse_args()
    return asyncio.run(main(dry_run=args.dry_run))


if __name__ == "__main__":
    raise SystemExit(cli())
