
"""
Create Paddle products and prices for BeanFlows.

Run once per environment (sandbox, then production).
Prints resulting price IDs as a .env snippet.

Usage:
    uv run python -m beanflows.scripts.setup_paddle
"""

import os
import sys

from dotenv import load_dotenv
from paddle_billing import Client as PaddleClient, Environment, Options
from paddle_billing.Entities.Shared import CurrencyCode, Money, TaxCategory
from paddle_billing.Resources.Prices.Operations import CreatePrice
from paddle_billing.Resources.Products.Operations import CreateProduct

load_dotenv()

PADDLE_API_KEY = os.getenv("PADDLE_API_KEY", "")
PADDLE_ENVIRONMENT = os.getenv("PADDLE_ENVIRONMENT", "sandbox")

if not PADDLE_API_KEY:
    print("ERROR: Set PADDLE_API_KEY in .env first")
    sys.exit(1)


PRODUCTS = [
    # Subscriptions
    {
        "name": "Starter",
        "env_key": "PADDLE_PRICE_STARTER",
        "price": 900,
        "currency": CurrencyCode.USD,
        "interval": "month",
        "type": "subscription",
    },
    {
        "name": "Pro",
        "env_key": "PADDLE_PRICE_PRO",
        "price": 2900,
        "currency": CurrencyCode.USD,
        "interval": "month",
        "type": "subscription",
    },
]


def main():
    env = Environment.SANDBOX if PADDLE_ENVIRONMENT == "sandbox" else Environment.PRODUCTION
    paddle = PaddleClient(PADDLE_API_KEY, options=Options(env))

    print(f"Creating products in {PADDLE_ENVIRONMENT}...\n")

    env_lines = []

    for spec in PRODUCTS:
        # Create product
        product = paddle.products.create(CreateProduct(
            name=spec["name"],
            tax_category=TaxCategory.Standard,
        ))
        print(f"  Product: {spec['name']} -> {product.id}")

        # Create price
        price_kwargs = {
            "description": spec["name"],
            "product_id": product.id,
            "unit_price": Money(str(spec["price"]), spec["currency"]),
        }

        if spec["type"] == "subscription":
            from paddle_billing.Entities.Shared import TimePeriod
            price_kwargs["billing_cycle"] = TimePeriod(interval="month", frequency=1)

        price = paddle.prices.create(CreatePrice(**price_kwargs))
        print(f"  Price:   {spec['env_key']} = {price.id}")

        env_lines.append(f"{spec['env_key']}={price.id}")

    print("\n# --- .env snippet ---")
    for line in env_lines:
        print(line)


if __name__ == "__main__":
    main()

