"""Idempotent Stripe catalog setup for Solace-Companion.

Creates the subscription product with two monthly prices:
- solace_intro_monthly  : $19.95 (months 1-6 of paid subscription)
- solace_standard_monthly: $29.95 (month 7 onward)
"""
import os
import stripe
from dotenv import load_dotenv
from pathlib import Path

load_dotenv(Path(__file__).parent / ".env")
stripe.api_key = os.environ.get("STRIPE_SECRET_KEY") or "sk_test_emergent"

CATALOG = [
    {
        "emergent_product_id": "solace_companion_plan",
        "name": "Solace Companion Membership",
        "tax_code": "txcd_10103001",  # SaaS
        "prices": [
            {"lookup_key": "solace_intro_monthly", "amount": 1995, "currency": "usd", "interval": "month"},
            {"lookup_key": "solace_standard_monthly", "amount": 2995, "currency": "usd", "interval": "month"},
        ],
    },
]


def get_or_create_product(entry):
    for p in stripe.Product.list(active=True).auto_paging_iter():
        if p.to_dict().get("metadata", {}).get("emergent_product_id") == entry["emergent_product_id"]:
            return p
    return stripe.Product.create(
        name=entry["name"],
        tax_code=entry.get("tax_code"),
        metadata={"managed_by": "emergent", "emergent_product_id": entry["emergent_product_id"]},
    )


def main():
    country = stripe.Account.retrieve().get("country", "US")
    print("Stripe account country:", country)
    for entry in CATALOG:
        product = get_or_create_product(entry)
        print("Product:", product.id, product.name)
        for p in entry["prices"]:
            existing = stripe.Price.list(lookup_keys=[p["lookup_key"]], active=True, limit=1).data
            if existing and (existing[0].unit_amount != p["amount"] or existing[0].currency != p["currency"]):
                stripe.Price.modify(existing[0].id, active=False)
                existing = []
            if not existing:
                kwargs = dict(
                    product=product.id,
                    unit_amount=p["amount"],
                    currency=p["currency"],
                    lookup_key=p["lookup_key"],
                    transfer_lookup_key=True,
                    recurring={"interval": p["interval"]},
                )
                price = stripe.Price.create(**kwargs)
                print("  Created price:", p["lookup_key"], price.id)
            else:
                print("  Price exists:", p["lookup_key"], existing[0].id)


if __name__ == "__main__":
    main()
