#!/usr/bin/env python3
"""MixLift Stripe Setup & Verification Script.

Checks your Stripe account for the required configuration and creates
anything that's missing. Run this once to get the payment flow working.

Usage:
    export STRIPE_SECRET_KEY=sk_test_...
    python scripts/setup_stripe.py
"""

import os
import sys

try:
    import stripe
except ImportError:
    print("ERROR: stripe package not installed. Run: pip install stripe")
    sys.exit(1)

stripe.api_key = os.environ.get("STRIPE_SECRET_KEY", "")
if not stripe.api_key:
    print("ERROR: Set STRIPE_SECRET_KEY environment variable first.")
    print("  export STRIPE_SECRET_KEY=sk_test_...")
    sys.exit(1)

WEBHOOK_URL = "https://api.mixlift.io/v1/webhooks/stripe"
REQUIRED_EVENTS = [
    "checkout.session.completed",
    "customer.subscription.updated",
    "customer.subscription.deleted",
    "invoice.payment_failed",
    "invoice.payment_succeeded",
]


def check_mode():
    """Report whether we're in test or live mode."""
    mode = "TEST" if stripe.api_key.startswith("sk_test_") else "LIVE"
    print(f"\n{'='*60}")
    print(f"  MixLift Stripe Setup — {mode} MODE")
    print(f"{'='*60}\n")
    return mode


def check_products():
    """Find or create the MixLift Pro product + $299/mo price."""
    print("1. Checking for MixLift product...")

    products = stripe.Product.list(limit=100)
    mixlift_product = None
    for p in products.data:
        if "mixlift" in (p.name or "").lower() or "mix lift" in (p.name or "").lower():
            mixlift_product = p
            break

    if mixlift_product:
        print(f"   ✓ Found product: '{mixlift_product.name}' ({mixlift_product.id})")
    else:
        print("   ✗ No MixLift product found. Creating one...")
        mixlift_product = stripe.Product.create(
            name="MixLift Pro",
            description="AI-native Marketing Mix Modeling. 8 channels, 50K rows, dollar-value insights, scenario mode.",
            metadata={"tier": "pro"},
        )
        print(f"   ✓ Created product: '{mixlift_product.name}' ({mixlift_product.id})")

    # Check for $299/mo price
    print("\n2. Checking for $299/mo recurring price...")
    prices = stripe.Price.list(product=mixlift_product.id, limit=100)
    growth_price = None
    for price in prices.data:
        if (
            price.unit_amount == 29900
            and price.recurring
            and price.recurring.interval == "month"
            and price.active
        ):
            growth_price = price
            break

    if growth_price:
        print(f"   ✓ Found price: ${growth_price.unit_amount/100}/mo ({growth_price.id})")
    else:
        print("   ✗ No $299/mo price found. Creating one...")
        growth_price = stripe.Price.create(
            product=mixlift_product.id,
            unit_amount=29900,
            currency="usd",
            recurring={"interval": "month"},
            metadata={"tier": "pro"},
        )
        print(f"   ✓ Created price: ${growth_price.unit_amount/100}/mo ({growth_price.id})")

    print(f"\n   Set this in your .env or environment:")
    print(f"   STRIPE_PRO_PRICE_ID={growth_price.id}")

    return mixlift_product, growth_price


def check_webhook():
    """Find or create the webhook endpoint."""
    print("\n3. Checking for webhook endpoint...")

    endpoints = stripe.WebhookEndpoint.list(limit=100)
    our_endpoint = None
    for ep in endpoints.data:
        if ep.url == WEBHOOK_URL and ep.status == "enabled":
            our_endpoint = ep
            break

    if our_endpoint:
        print(f"   ✓ Found webhook: {our_endpoint.url}")
        print(f"     Events: {', '.join(our_endpoint.enabled_events)}")

        # Check if all required events are enabled
        missing = [e for e in REQUIRED_EVENTS if e not in our_endpoint.enabled_events]
        if missing:
            print(f"   ⚠ Missing events: {', '.join(missing)}. Updating...")
            all_events = list(set(our_endpoint.enabled_events + REQUIRED_EVENTS))
            stripe.WebhookEndpoint.modify(
                our_endpoint.id,
                enabled_events=all_events,
            )
            print("   ✓ Webhook events updated.")
    else:
        print(f"   ✗ No webhook for {WEBHOOK_URL}. Creating one...")
        our_endpoint = stripe.WebhookEndpoint.create(
            url=WEBHOOK_URL,
            enabled_events=REQUIRED_EVENTS,
            description="MixLift License API",
        )
        print(f"   ✓ Created webhook: {our_endpoint.url}")
        print(f"\n   ⚠ IMPORTANT: New webhook secret generated!")
        print(f"     Secret: {our_endpoint.secret}")
        print(f"\n     You MUST update the Fly.io secret:")
        print(f"     cd /Users/felix/software-projects/mixlift-api")
        print(f"     fly secrets set STRIPE_WEBHOOK_SECRET={our_endpoint.secret}")

    return our_endpoint


def check_payment_link(product, price):
    """Find or create a payment link."""
    print("\n4. Checking for payment link...")

    # List existing payment links
    links = stripe.PaymentLink.list(limit=100)
    our_link = None
    for link in links.data:
        if link.active:
            # Check if this link uses our price
            line_items = stripe.PaymentLink.list_line_items(link.id, limit=10)
            for item in line_items.data:
                if item.price and item.price.id == price.id:
                    our_link = link
                    break
        if our_link:
            break

    if our_link:
        print(f"   ✓ Found payment link: {our_link.url}")
    else:
        print("   ✗ No payment link found. Creating one...")
        our_link = stripe.PaymentLink.create(
            line_items=[{"price": price.id, "quantity": 1}],
            after_completion={
                "type": "redirect",
                "redirect": {"url": "https://api.mixlift.io/welcome?session_id={CHECKOUT_SESSION_ID}"},
            },
            metadata={"product": "mixlift_pro"},
        )
        print(f"   ✓ Created payment link: {our_link.url}")

    return our_link


def verify_api_health():
    """Verify the license API is responding."""
    print("\n5. Verifying License API...")
    try:
        import httpx

        resp = httpx.get("https://api.mixlift.io/health", timeout=5.0)
        if resp.status_code == 200:
            print(f"   ✓ License API healthy: {resp.json()}")
        else:
            print(f"   ✗ License API returned {resp.status_code}: {resp.text}")
    except ImportError:
        print("   ⚠ httpx not installed, skipping API health check")
    except Exception as e:
        print(f"   ✗ License API unreachable: {e}")


def print_summary(mode, product, price, webhook, payment_link):
    """Print final summary with next steps."""
    print(f"\n{'='*60}")
    print("  SUMMARY")
    print(f"{'='*60}")
    print(f"""
  Mode:          {mode}
  Product:       {product.name} ({product.id})
  Price:         ${price.unit_amount/100}/mo ({price.id})
  Webhook:       {webhook.url}
  Payment Link:  {payment_link.url}

  PAYMENT FLOW:
  1. User visits payment link above (or mixlift.io/pricing)
  2. Stripe Checkout collects payment
  3. Webhook fires → License API creates license key
  4. License key emailed to customer via Resend
  5. Customer configures MCP with license key
  6. MCP validates against api.mixlift.io → unlocks Pro tier
""")

    print("  NEXT STEPS:")
    print(f"  • Update mixlift.io/pricing to redirect to: {payment_link.url}")
    print(f"  • Update MCP upgrade messages to use: {payment_link.url}")
    if mode == "TEST":
        print("  • Test with Stripe test card: 4242 4242 4242 4242")
        print("  • When ready for real payments, re-run with live key:")
        print("    export STRIPE_SECRET_KEY=sk_live_...")
        print("    python scripts/setup_stripe.py")
    print()


def main():
    mode = check_mode()
    product, price = check_products()
    webhook = check_webhook()
    payment_link = check_payment_link(product, price)
    verify_api_health()
    print_summary(mode, product, price, webhook, payment_link)


if __name__ == "__main__":
    main()
