#!/usr/bin/env python3
"""
patch_stripe_webhook.py — Auto-patch Stripe webhook URL when cloudflared tunnel rotates.

Called by bridge_watchdog.sh when /tmp/tunnel_url_8400.txt changes.
Usage: python3 patch_stripe_webhook.py <new_tunnel_url>

Strategy:
- Find the Sunaiva AI Memory webhook in Stripe (by description or URL pattern)
- Delete it and create a new one at the new URL
- Update /mnt/e/genesis-system/Sunaiva/ai-memory/.env.production with the new secret
- Write the webhook ID to /tmp/stripe_webhook_id_8400.txt for next run
"""

import sys
import os
import re
import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger(__name__)

ENV_FILE = "/mnt/e/genesis-system/Sunaiva/ai-memory/.env.production"
WEBHOOK_ID_FILE = "/tmp/stripe_webhook_id_8400.txt"
STRIPE_KEY = "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"

WEBHOOK_PATH = "/api/billing/webhook"
EVENTS = [
    "checkout.session.completed",
    "customer.subscription.created",
    "customer.subscription.updated",
    "customer.subscription.deleted",
    "invoice.paid",
    "invoice.payment_failed",
]


def update_env_file(new_secret: str, new_webhook_id: str, new_url: str) -> None:
    with open(ENV_FILE, "r") as f:
        content = f.read()

    # Update STRIPE_WEBHOOK_SECRET
    content = re.sub(
        r"STRIPE_WEBHOOK_SECRET=.*",
        f"STRIPE_WEBHOOK_SECRET={new_secret}",
        content,
    )

    # Update the comment line showing endpoint info
    content = re.sub(
        r"# Webhook endpoint: we_\S+",
        f"# Webhook endpoint: {new_webhook_id}",
        content,
    )

    with open(ENV_FILE, "w") as f:
        f.write(content)

    log.info(f"Updated {ENV_FILE} with new webhook secret")


def restart_sunaiva_api(port: int = 8400) -> None:
    """Restart the Sunaiva API tmux session to pick up new env vars."""
    import subprocess
    genesis = "/mnt/e/genesis-system"
    cmd = (
        f"tmux kill-session -t sunaiva-api 2>/dev/null; "
        f"tmux new-session -d -s sunaiva-api -x 220 -y 50 "
        f"'cd {genesis}/Sunaiva/ai-memory/server && "
        f"set -a && source {genesis}/Sunaiva/ai-memory/.env.production && set +a && "
        f"python3 -m uvicorn main:app --host 0.0.0.0 --port {port} "
        f"2>&1 | tee -a {genesis}/logs/sunaiva_api.log'"
    )
    subprocess.run(cmd, shell=True)
    log.info("Sunaiva API restarted in tmux sunaiva-api")


def main():
    if len(sys.argv) < 2:
        print("Usage: patch_stripe_webhook.py <new_tunnel_url>")
        sys.exit(1)

    new_tunnel_url = sys.argv[1].strip().rstrip("/")
    new_webhook_url = new_tunnel_url + WEBHOOK_PATH

    try:
        import stripe
        stripe.api_key = STRIPE_KEY
    except ImportError:
        log.error("stripe package not installed")
        sys.exit(1)

    # Read previous webhook ID if known
    old_webhook_id = None
    if os.path.exists(WEBHOOK_ID_FILE):
        with open(WEBHOOK_ID_FILE) as f:
            old_webhook_id = f.read().strip()

    # Delete old webhook if we know its ID
    if old_webhook_id:
        try:
            stripe.WebhookEndpoint.delete(old_webhook_id)
            log.info(f"Deleted old webhook: {old_webhook_id}")
        except Exception as e:
            log.warning(f"Could not delete old webhook {old_webhook_id}: {e}")

    # Create new webhook at new URL
    try:
        endpoint = stripe.WebhookEndpoint.create(
            url=new_webhook_url,
            enabled_events=EVENTS,
            description="Sunaiva AI Memory - cloudflared tunnel (auto-patched)",
        )
        log.info(f"Created webhook {endpoint.id} → {endpoint.url}")

        # Save new ID
        with open(WEBHOOK_ID_FILE, "w") as f:
            f.write(endpoint.id)

        # Update .env.production
        update_env_file(endpoint.secret, endpoint.id, new_webhook_url)

        # Restart API to pick up new secret
        restart_sunaiva_api()

        print(f"PATCHED: {endpoint.id} → {new_webhook_url}")

    except Exception as e:
        log.error(f"Failed to create new webhook: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
