#!/usr/bin/env bash
set -uo pipefail

python3 - <<'PY'
import json
import urllib.request
from datetime import datetime, timezone
from pathlib import Path


def parse_time(value):
    if not value:
        return None
    return datetime.fromisoformat(value.replace("Z", "+00:00"))


def format_time(value):
    dt = parse_time(value)
    if not dt:
        return "-"
    return dt.astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")


def format_remaining(value):
    dt = parse_time(value)
    if not dt:
        return "-"

    remaining = dt - datetime.now(timezone.utc)
    seconds = int(remaining.total_seconds())
    if seconds <= 0:
        return "expired"

    days, seconds = divmod(seconds, 86400)
    hours = seconds // 3600
    if days:
        return f"{days} day(s), {hours} hour(s)"
    return f"{hours} hour(s)"


def format_response(raw):
    try:
        data = json.loads(raw)
    except json.JSONDecodeError:
        return raw

    credits = data.get("credits", [])
    lines = [
        "Codex rate limit reset credits",
        "================================",
        f"Available: {data.get('available_count', 0)}",
        f"Total earned: {data.get('total_earned_count', 0)}",
        "",
    ]

    if not credits:
        lines.append("No credits found.")
        return "\n".join(lines)

    for index, credit in enumerate(credits, start=1):
        credit_id = credit.get("id", "")
        short_id = credit_id.rsplit("_", 1)[-1][:8] if credit_id else "-"

        lines.extend(
            [
                f"{index}. {credit.get('title', 'Untitled credit')}",
                f"   Status:      {credit.get('status', '-')}",
                f"   Expires:     {format_time(credit.get('expires_at'))}",
                f"   Time left:   {format_remaining(credit.get('expires_at'))}",
                f"   Granted:     {format_time(credit.get('granted_at'))}",
                f"   Short ID:    {short_id}",
            ]
        )

        description = credit.get("description")
        if description:
            lines.append(f"   Note:        {description}")
        lines.append("")

    return "\n".join(lines).rstrip()


auth = json.loads(Path("~/.codex/auth.json").expanduser().read_text())
token = auth["tokens"]["access_token"]
account = auth["tokens"]["account_id"]

req = urllib.request.Request(
    "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",
    headers={
        "Authorization": f"Bearer {token}",
        "ChatGPT-Account-ID": account,
        "originator": "Codex Desktop",
    },
)

raw_response = urllib.request.urlopen(req).read().decode()
print(format_response(raw_response))
PY

status=$?
printf '\nPress Enter to close this window...'
read -r _
exit "$status"
