"""Print one CSV row per listed model, using the current public prices.

    python3 export-model-prices.py > model-prices.csv

All prices are USD. Blank fields do not have a quoted price for that unit.
Resolution tiers and long-context rates retain the structure of the catalog.
"""
import csv
from datetime import datetime, timezone
import json
import sys
from urllib.request import Request, urlopen

SOURCE = "https://kunavo.com/pricing.json"


def main():
    request = Request(SOURCE, headers={"Accept": "application/json", "User-Agent": "kunavo-pricing-example/1"})
    with urlopen(request, timeout=20) as response:
        catalog = json.load(response)
    observed = datetime.now(timezone.utc).isoformat(timespec="seconds")
    writer = csv.writer(sys.stdout)
    writer.writerow(["observed_utc", "model_id", "category", "endpoint", "capabilities",
                     "currency", "unit", "input", "output", "cache_read", "cache_write",
                     "per_unit", "duration_seconds", "long_context_json", "tiers_json", "source"])
    for model in catalog["models"]:
        price = model["pricing"]
        writer.writerow([observed, model["id"], model["category"], model["endpoint"],
                         "|".join(model["capabilities"]), catalog["currency"], price["unit"],
                         price["input"], price["output"], price["cache_read"], price["cache_write"],
                         price["per_unit"], price["duration_seconds"],
                         json.dumps(price["long_context"]) if price["long_context"] is not None else "",
                         json.dumps(price["tiers"]) if price["tiers"] is not None else "", SOURCE])


if __name__ == "__main__":
    main()
