#!/usr/bin/env python3
from __future__ import annotations
import csv
import json
import subprocess
from pathlib import Path

BASE = Path(__file__).resolve().parent
CATALOG = list(csv.DictReader((BASE / "catalog.csv").open()))

def run(cmd: list[str]) -> dict:
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise SystemExit(f"Command failed: {' '.join(cmd)}\n\nSTDERR:\n{result.stderr}\nSTDOUT:\n{result.stdout}")
    try:
        return json.loads(result.stdout)
    except json.JSONDecodeError as exc:
        raise SystemExit(f"Expected JSON from Stripe CLI, got:\n{result.stdout}") from exc

products = []
prices = []

for row in CATALOG:
    if row.get("active", "").lower() != "true":
        continue
    product = run([
        "stripe", "products", "create",
        f"--name={row['name']}",
        f"--description={row['description']}",
        f"--metadata[sku]={row['sku']}",
        f"--metadata[category]={row['category']}",
        f"--metadata[slug]={row['slug']}",
        "--metadata[dev]=DEV3",
    ])
    price = run([
        "stripe", "prices", "create",
        f"--unit-amount={row['amount_cents']}",
        f"--currency={row['currency']}",
        f"--product={product['id']}",
        f"--nickname=DEV3 {row['sku']}",
        f"--metadata[sku]={row['sku']}",
        "--metadata[dev]=DEV3",
    ])
    products.append(product)
    prices.append({
        "sku": row["sku"],
        "name": row["name"],
        "product_id": product["id"],
        "price_id": price["id"],
        "unit_amount": price.get("unit_amount"),
        "currency": price.get("currency"),
    })

(BASE / "stripe_products.json").write_text(json.dumps(products, indent=2))
(BASE / "stripe_prices.json").write_text(json.dumps(prices, indent=2))
print(f"Created {len(products)} products and {len(prices)} prices for DEV3.")
