#!/usr/bin/env python3
# summary: Read or refresh usage for your AI accounts.
"""Per-account AI usage: refresh saved readings, or show them without network access."""
import argparse
import contextlib
import copy
import datetime as dt
import fcntl
import hashlib
import importlib.machinery
import importlib.util
import io
import json
import math
import os
import re
import select
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path

sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_ai_config as ai_config

loader = importlib.machinery.SourceFileLoader("ai_accounts", str(Path(__file__).resolve().with_name("starchaser-ai-account")))
spec = importlib.util.spec_from_loader(loader.name, loader)
accounts = importlib.util.module_from_spec(spec)
loader.exec_module(accounts)
STATE = Path.home() / ".local/state/starchaser/ai-usage"
INTERVAL = 300
ENDPOINT = "https://api.anthropic.com/api/oauth/usage"


class UsageError(Exception):
    def __init__(self, reason, auth=False):
        super().__init__(reason)
        self.auth = auth


def obj(value):
    return value if isinstance(value, dict) else {}


def number(value):
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value < 1e15:
        return None
    return value


def label(value):
    return re.sub(r"[^A-Za-z0-9 ._()/+-]", "", value)[:80] if isinstance(value, str) else ""


def inside(home, path):
    # Reject links escaping an account, including an account home linked to Personal.
    if home.is_symlink() or home.resolve() != home.absolute() or not path.resolve().is_relative_to(home.resolve()):
        raise UsageError("This account's files point outside its home.")
    return path


def read_json(path, home=None, limit=2 * 1024 * 1024):
    if home is not None:
        inside(home, path)
    try:
        with path.open() as stream:
            return obj(json.loads(stream.read(limit) if limit is not None else stream.read()))
    except FileNotFoundError:
        return {}
    except (OSError, ValueError):
        raise UsageError("A saved file couldn't be read.") from None


def timestamp(value):
    n = number(value)
    if n is not None:
        return n / 1000 if n > 1e12 else n
    if isinstance(value, str):
        try:
            parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
            return parsed.timestamp() if parsed.tzinfo else None
        except (ValueError, OverflowError, OSError):
            pass
    return None


def window(name, percent, reset):
    n = number(percent)
    if n is None:
        return None
    return {"label": name, "percent": min(100, n), "resetsAt": timestamp(reset)}


def claude_windows(data):
    result = []
    for key, name in (("five_hour", "Session (5-hour)"), ("seven_day", "Weekly")):
        bucket = obj(data.get(key))
        entry = window(name, bucket.get("utilization"), bucket.get("resets_at"))
        if entry:
            result.append(entry)
    seen = set()
    for entry in data.get("limits", []) if isinstance(data.get("limits"), list) else []:
        entry = obj(entry)
        model = obj(obj(entry.get("scope")).get("model"))
        name = label(model.get("display_name") or model.get("id"))
        kind = label(entry.get("kind"))
        span = "Weekly" if "week" in kind or "seven_day" in kind else "Session" if "hour" in kind or "session" in kind else "Monthly" if "month" in kind else kind
        key = (name.lower(), span)
        w = window((name + " " + span).strip(), entry.get("percent"), entry.get("resets_at"))
        if name and key not in seen and w:
            result.append(w)
            seen.add(key)
    for key, bucket in data.items():
        if key.startswith("seven_day_") and key != "seven_day_oauth_apps":
            name = label(key.removeprefix("seven_day_")).title()
            w = window(name + " Weekly", obj(bucket).get("utilization"), obj(bucket).get("resets_at"))
            if w and (name.lower(), "Weekly") not in seen:
                result.append(w)
    return result


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def claude(home):
    auth = obj(read_json(home / ".credentials.json", home).get("claudeAiOauth"))
    token = auth.get("accessToken")
    if not isinstance(token, str) or not token:
        raise UsageError("No OAuth sign-in in this account home. API keys don't expose subscription limits.", True)
    expiry = timestamp(auth.get("expiresAt"))
    if expiry and expiry <= time.time():
        raise UsageError("Usage updates the next time you open Claude Code.")
    request = urllib.request.Request(ENDPOINT, headers={"Authorization": "Bearer " + token,
                                   "anthropic-beta": "oauth-2025-04-20", "Accept": "application/json"})
    try:
        # No redirects, endpoint overrides, or inherited proxies carrying credentials elsewhere.
        opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
        with opener.open(request, timeout=12) as response:
            data = obj(json.loads(response.read(2 * 1024 * 1024)))
    except urllib.error.HTTPError as error:
        error.close()
        if error.code in (401, 403):
            raise UsageError("Anthropic refused this sign-in.", True) from None
        if error.code == 429:
            raise UsageError("Anthropic is limiting usage checks. Try again later.") from None
        raise UsageError(f"Anthropic returned HTTP {error.code}.") from None
    except (OSError, ValueError, urllib.error.URLError):
        raise UsageError("Anthropic couldn't be reached or returned an invalid reply.") from None
    windows = claude_windows(data)
    if not windows:
        raise UsageError("Anthropic returned no usable limit windows.")
    # Plan is allowlisted: no other credential fields enter the record.
    plan = auth.get("subscriptionType")
    plan = plan.title() if plan in ("free", "pro", "max", "team", "enterprise") else ""
    return {"windows": windows, "plan": plan, "balance": None, "note": ""}


def rpc(proc, ident, method, params=None):
    proc.stdin.write(json.dumps({"id": ident, "method": method, "params": params or {}}).encode() + b"\n")
    proc.stdin.flush()
    pending = getattr(proc, "pending", b"")
    deadline = time.monotonic() + 12
    try:
        while time.monotonic() < deadline:
            while b"\n" in pending:
                line, pending = pending.split(b"\n", 1)
                try:
                    data = obj(json.loads(line))
                except ValueError:
                    continue
                if data.get("id") == ident:
                    if "error" in data:
                        # Classify, never return server text (it may echo a credential).
                        error = obj(data["error"])
                        auth = any(s in str(error.get("message", "")).lower() for s in ("auth", "sign in", "401", "403", "token expired"))
                        raise UsageError("Codex refused this sign-in." if auth else "Codex couldn't read rate limits. Check its connection and CLI version.", auth)
                    return obj(data.get("result"))
            if len(pending) > 2 * 1024 * 1024:
                raise UsageError("Codex returned an invalid reply.")
            if select.select([proc.stdout], [], [], max(0, deadline - time.monotonic()))[0]:
                chunk = os.read(proc.stdout.fileno(), 65536)
                if not chunk:
                    raise UsageError("Codex app-server stopped before answering.")
                pending += chunk
        raise UsageError("Codex app-server timed out.")
    finally:
        proc.pending = pending


def codex_result(data):
    buckets = obj(data.get("rateLimitsByLimitId")) or {"codex": obj(data.get("rateLimits"))}
    if not any(obj(b) for b in buckets.values()):
        raise UsageError("Codex returned no rate-limit information.")
    windows, plan, balance = [], "", None
    for key, raw in sorted(buckets.items(), key=lambda pair: pair[0] != "codex"):
        bucket = obj(raw)
        plan = plan or label(bucket.get("planType"))
        for kind in ("primary", "secondary"):
            part = obj(bucket.get(kind))
            minutes = number(part.get("windowDurationMins"))
            span = "Weekly" if minutes == 10080 else f"{minutes / 60:g}-hour" if minutes and minutes % 60 == 0 else f"{minutes:g}-minute" if minutes else "Limit"
            name = ((label(bucket.get("limitName") or key) + " ") if key != "codex" else "") + span
            w = window(name, part.get("usedPercent"), part.get("resetsAt"))
            if w:
                windows.append(w)
        credits = obj(bucket.get("credits"))
        amount = credits.get("balance")
        if isinstance(amount, str):
            try:
                amount = float(amount)
            except ValueError:
                amount = None
        if balance is None and number(amount) is not None:
            balance = amount
    return {"windows": windows, "plan": plan, "balance": balance,
            "note": "" if windows else "This account reports no quota windows."}


def codex(home):
    auth = read_json(home / "auth.json", home)
    if not auth:
        raise UsageError("No file-based sign-in in this account home. External keychains can't be measured here.", True)
    if auth.get("auth_mode") == "apikey" or (auth.get("OPENAI_API_KEY") and not auth.get("tokens")):
        return {"windows": [], "plan": "API key", "balance": None, "note": "API key accounts don't expose ChatGPT subscription limits."}
    binary = accounts.binary("codex")
    if not binary:
        raise UsageError("Install Codex from Software to read its limits.")
    inside(home, home / "config.toml")
    # Only the target home's file store. No ambient keys, access tokens, proxy,
    # auth broker, debug logging, or project configuration inherited from a terminal.
    env = {"HOME": str(Path.home()), "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
           "LANG": "C.UTF-8", "CODEX_HOME": str(home), "RUST_LOG": "off"}
    args = [binary, "-c", 'cli_auth_credentials_store="file"',
            "-c", 'chatgpt_base_url="https://chatgpt.com/backend-api/"',
            "-c", 'openai_base_url="https://api.openai.com/v1"',
            "-c", 'otel.exporter="none"', "-c", 'otel.trace_exporter="none"', "app-server"]
    with subprocess.Popen(args, cwd="/", env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                          stderr=subprocess.DEVNULL) as proc:
        try:
            rpc(proc, 1, "initialize", {"clientInfo": {"name": "starchaser ai usage", "version": "1"}})
            proc.stdin.write(b'{"method":"initialized"}\n')
            proc.stdin.flush()
            return codex_result(rpc(proc, 2, "account/rateLimits/read"))
        finally:
            proc.terminate()
            try:
                proc.wait(timeout=2)
            except subprocess.TimeoutExpired:
                proc.kill()
                proc.wait()


def hermes(home):
    return {"windows": [], "plan": "", "balance": None,
            "note": "Hermes has no shared subscription quota. Limits and balances belong to its selected provider; local tokens are shown below."}


COLLECTORS = {"claude": claude, "codex": codex, "hermes": hermes}


def local_stats(tool, home):
    """All recorded tokens in this tool home, not an estimate of a provider quota."""
    totals = dict(input=0, output=0, cacheRead=0, cacheWrite=0)
    def add(values):
        for key, value in zip(totals, values):
            totals[key] += int(number(value) or 0)
    if tool == "hermes":
        path = inside(home, home / "state.db")
        if path.exists():
            with contextlib.closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True, timeout=2)) as conn:
                tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
                if "session_model_usage" not in tables:
                    raise UsageError("This Hermes database doesn't record token counts yet.")
                for row in conn.execute("SELECT input_tokens, output_tokens, cache_read_tokens, cache_write_tokens FROM session_model_usage"):
                    add(row)
    else:
        roots = [home / "projects"] if tool == "claude" else [home / "sessions", home / "archived_sessions"]
        accounts.private_dir(STATE)
        cache_path = STATE / (".tokens-" + tool + "-" + hashlib.sha256(str(home).encode()).hexdigest()[:20] + ".cache")
        try:
            cache = read_json(cache_path, STATE, limit=None)
        except UsageError:
            cache = {}
        # Version 1 could persist inflated deltas after rereading an unterminated Codex record.
        previous = obj(cache.get("files")) if cache.get("version") == 2 else {}
        files, seen = {}, {}
        for root in roots:
            inside(home, root)
            for path in sorted(root.rglob("*.jsonl")):
                inside(home, path)
                stat = path.stat()
                prior = obj(previous.get(str(path)))
                offset = prior.get("offset", 0)
                append = (prior.get("inode") == stat.st_ino and isinstance(offset, int) and 0 <= offset <= stat.st_size
                          and (stat.st_size > prior.get("size", 0) or stat.st_mtime_ns == prior.get("mtime")))
                entry = dict(prior) if append else {"offset": 0, "lines": 0, "values": {}, "session": str(path), "cumulative": [0, 0, 0, 0]}
                entry["values"] = dict(obj(entry.get("values")))
                session, cumulative = entry["session"], entry["cumulative"]
                values_seen = entry["values"]
                checkpoint = None
                with path.open("rb") as stream:
                    stream.seek(entry["offset"])
                    while True:
                        line = stream.readline()
                        if not line:
                            break
                        if not line.endswith(b"\n"):
                            try:
                                json.loads(line)
                            except ValueError:
                                break
                            # A valid final record counts now, but is reread until its newline arrives.
                            # These counters may have changed on earlier lines in this same read.
                            entry.update(session=session, cumulative=cumulative)
                            checkpoint = copy.deepcopy(entry)
                        line_number = entry["lines"]
                        entry["lines"] += 1
                        entry["offset"] = stream.tell()
                        try:
                            data = obj(json.loads(line))
                        except ValueError:
                            if line.strip() and line.endswith(b"\n"):
                                raise UsageError("A session contains an unreadable record.") from None
                            continue  # A running session may have an unfinished last line.
                        if tool == "claude":
                            message = obj(data.get("message"))
                            usage = obj(message.get("usage"))
                            if data.get("type") != "assistant" or not usage:
                                continue
                            ident = message.get("id") or data.get("uuid")
                            # Streamed blocks may repeat a message with updated final counters.
                            key = (str(ident), str(data.get("requestId", ""))) if ident else (str(path), line_number)
                            values = [int(number(usage.get(k)) or 0) for k in ("input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")]
                        else:
                            payload = obj(data.get("payload"))
                            if data.get("type") == "session_meta":
                                session = str(payload.get("id") or session)
                            if data.get("type") != "event_msg" or payload.get("type") != "token_count":
                                continue
                            info = obj(payload.get("info"))
                            usage = obj(info.get("total_token_usage"))
                            if not usage:
                                continue
                            cached = int(number(usage.get("cached_input_tokens")) or 0)
                            values = [max(0, int(number(usage.get("input_tokens")) or 0) - cached),
                                      int(number(usage.get("output_tokens")) or 0), cached, 0]
                            # Cumulative counters repeat on notifications and resets on resume.
                            delta = [max(0, a - b) if a >= b else a for a, b in zip(values, cumulative)]
                            cumulative = values
                            key = (session, str(data.get("timestamp")), tuple(values))
                            values = delta
                        key = json.dumps(key)
                        values_seen[key] = [max(a, b) for a, b in zip(values_seen.get(key, [0] * 4), values)]
                entry.update(session=session, cumulative=cumulative)
                saved_entry = checkpoint or entry
                saved_entry.update(inode=stat.st_ino, size=stat.st_size, mtime=stat.st_mtime_ns)
                files[str(path)] = saved_entry
                for key, values in values_seen.items():
                    seen[key] = [max(a, b) for a, b in zip(seen.get(key, [0] * 4), values)]
        ai_config.write(cache_path, {"version": 2, "files": files})
        for values in seen.values():
            add(values)
    return {**totals, "total": sum(totals.values()), "scope": "Recorded local tokens (all time)", "fetchedAt": time.time()}


def record_id(tool, account):
    # Stable across rename, with no account name or credential in the filename.
    return tool + "-" + (hashlib.sha256(account["home"].encode()).hexdigest()[:20] if account["home"] else "personal")


def base_record(tool, account, active):
    return {"version": 1, "id": record_id(tool, account), "tool": tool, "label": accounts.TOOLS[tool]["label"],
            "account": account["name"], "active": account["home"] == active, "managed": bool(account["home"]),
            "installed": bool(accounts.binary(tool)), "ready": bool(account.get("ready")),
            "windows": [], "plan": "", "balance": None, "fetchedAt": 0, "attemptedAt": 0,
            "status": "pending", "reason": "Usage hasn't been checked yet.", "note": "", "authRequired": False,
            "hasAuth": False, "authStamp": [], "local": {}, "localError": ""}


def saved(tool, account, active):
    result = base_record(tool, account, active)
    try:
        old = read_json(STATE / (result["id"] + ".json"), STATE)
    except UsageError:
        old = {}
    if old.get("version") == 1:
        for key, default in result.items():
            if key in ("version", "id", "tool", "label", "account", "active", "managed", "installed", "ready"):
                continue  # Metadata and filenames always come from the registry.
            value = old.get(key, default)
            if default is None or type(value) is type(default) or type(default) is int and number(value) is not None:
                result[key] = value
        result["windows"] = [w for w in result["windows"] if isinstance(w, dict)
                             and isinstance(w.get("label"), str) and number(w.get("percent")) is not None
                             and (w.get("resetsAt") is None or number(w.get("resetsAt")) is not None)]
    result.update(account=account["name"], active=account["home"] == active)
    return result


def write_record(record):
    fd, tmp = tempfile.mkstemp(prefix=".record-", dir=STATE)
    try:
        with os.fdopen(fd, "w") as stream:
            json.dump(record, stream, allow_nan=False)
            stream.write("\n")
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(tmp, STATE / (record["id"] + ".json"))
    finally:
        Path(tmp).unlink(missing_ok=True)


def collect(tool, account, active, force=False):
    old = saved(tool, account, active)
    now = time.time()
    result = dict(old, attemptedAt=now, reason="", localError="", authRequired=False)
    try:
        home = accounts.account_home(tool, account) or Path.home() / ("." + tool)
        inside(home, home)
        # Only presence enters the record. No credential contents are copied.
        names = {"claude": [".credentials.json"], "codex": ["auth.json"], "hermes": ["auth.json", ".env"]}[tool]
        stamps = []
        for name in names:
            path = inside(home, home / name)
            if path.is_file():
                st = path.stat()
                stamps.append([name, st.st_ino, st.st_mtime_ns, st.st_size])
        # A changed login must never inherit the previous identity's cached quotas.
        # Store only file metadata, never a token, token hash, email, or account ID.
        if stamps != old["authStamp"]:
            result.update(windows=[], plan="", balance=None, fetchedAt=0, authStamp=stamps)
        # A Claude Code or Codex account with no sign-in has nothing to ask a server, so every check reads it
        # again: Refresh usage then says "Checked just now" instead of an old time that looks like it did nothing.
        elif not force and (stamps or tool == "hermes") and 0 <= now - old["attemptedAt"] < INTERVAL:
            return old
        result["hasAuth"] = bool(stamps)
        try:
            result["local"] = local_stats(tool, home)
        except (OSError, sqlite3.Error, UsageError):
            result["localError"] = "Couldn't refresh local tokens. A session file is unreadable or uses an unsupported format."
        result.update(COLLECTORS[tool](home))
        result.update(status="ok", fetchedAt=now)
    except UsageError as error:
        result.update(status="auth" if error.auth else "error", reason=str(error), authRequired=error.auth)
    except (OSError, ValueError, accounts.AccountError):
        result.update(status="error", reason="The account home or tool couldn't be read. Check its installation and files.")
    write_record(result)
    return result


def auto_refresh_enabled():
    try:
        return ai_config.read(Path.home() / ".config/starchaser/ai.json").get("usageAutoRefresh") is True
    except OSError:
        return False


def set_auto_refresh(enabled):
    ai_config.update(Path.home() / ".config/starchaser/ai.json", lambda data: data.update(usageAutoRefresh=enabled))


def records(refresh=False, selected_tool=None, selected_account=None, force=False):
    # Match the account manager's lock and leases so removal cannot race a probe.
    with accounts.registry_lock():
        listing = [(tool, accounts.read_registry(tool)) for tool in accounts.TOOLS]
    if selected_tool and selected_account:
        registry = next(registry for tool, registry in listing if tool == selected_tool)
        if not any(a["name"].casefold() == selected_account.casefold() for a in registry["accounts"]):
            raise UsageError(f"No account named {selected_account}. Run 'starchaser ai account list {selected_tool}' to see available accounts.")
    out = []
    valid = set()
    for tool, registry in listing:
        if selected_tool and tool != selected_tool:
            continue
        for account in registry["accounts"]:
            if selected_account and account["name"].casefold() != selected_account.casefold():
                continue
            valid.add(record_id(tool, account) + ".json")
            if refresh:
                with accounts.registry_lock():
                    current = accounts.read_registry(tool)
                    account = next((a for a in current["accounts"] if a["home"] == account["home"]), None)
                    if account is None:
                        continue
                    try:
                        handle = accounts.lease(tool, account)
                    except accounts.AccountError as error:
                        # A sign-in holds this account exclusively. Keep its last reading and continue
                        # checking the other accounts instead of reporting a registry-permissions failure.
                        record = saved(tool, account, current["active"])
                        record.update(status="error", reason=f"This account is busy. {error} Other accounts can still update.")
                        out.append(record)
                        continue
                with handle:
                    out.append(collect(tool, account, current["active"], force=force))
            else:
                out.append(saved(tool, account, registry["active"]))
    if refresh and not selected_tool and not selected_account:
        for path in STATE.glob("*.json"):
            if re.fullmatch(r"(claude|codex|hermes)-(personal|[a-f0-9]{20})\.json", path.name) and path.name not in valid:
                path.unlink()
    return out


def sign_in(tool, name):
    """The same sign-in terminal as Settings > AI > Accounts: a web browser first, and Ctrl+C closes it."""
    with accounts.registry_lock():
        account = accounts.find_account(accounts.read_registry(tool), name)
    with contextlib.redirect_stdout(io.StringIO()):
        accounts.terminal("signin" if account["ready"] else "add", tool, account["name"])


def legacy_document(data):
    """Keep the original no-argument JSON contract for menu and external callers."""
    agents = []
    for record in data:
        if not accounts.binary(record["tool"]):
            continue
        limits = [dict(w, resetsAt=dt.datetime.fromtimestamp(w["resetsAt"], dt.timezone.utc).isoformat()
                       if w["resetsAt"] is not None else "") for w in record["windows"]]
        agents.append({"id": record["tool"], "name": {"codex": "Codex"}.get(record["tool"], record["label"]), "plan": record["plan"],
                       "limits": limits, "error": record["reason"], "account": record["account"],
                       "active": record["active"]})
    return {"updated": int(time.time()), "agents": agents}


def main():
    parser = argparse.ArgumentParser(prog=os.environ.get("STARCHASER_AI_USAGE_PROG", "starchaser ai usage"), description=__doc__,
        epilog="With no arguments, refresh and print JSON with an update time and usage for installed tools' accounts. "
               "For saved readings without network access, use: starchaser ai usage show. "
               "With --json alone, show saved readings as an account list for scripts.")
    parser.add_argument("command", choices=("refresh", "show", "signin", "preferences", "auto-on", "auto-off"), nargs="?", default=None,
                        help="refresh: check usage and save readings; show: read saved readings without refreshing; "
                             "signin: open a terminal to sign in to the named tool and account")
    parser.add_argument("tool", choices=accounts.TOOLS, nargs="?", help="limit readings to this tool; required for signin")
    parser.add_argument("account", nargs="?", help="account name; required for signin")
    parser.add_argument("--json", action="store_true", help="print an account list as JSON for scripts instead of text")
    parser.add_argument("--force", action="store_true", help="refresh even if checked in the last five minutes")
    parser.add_argument("--background", action="store_true", help="refresh only when automatic usage checks are turned on")
    args = parser.parse_args(["--help"] if sys.argv[1:] == ["help"] else None)
    legacy = args.command is None and not args.json
    args.command = args.command or ("refresh" if legacy or args.force else "show")
    if args.force and args.command != "refresh":
        parser.error("--force needs refresh")
    os.umask(0o077)
    try:
        if args.command in ("preferences", "auto-on", "auto-off"):
            if args.command != "preferences":
                set_auto_refresh(args.command == "auto-on")
            print(json.dumps({"automatic": auto_refresh_enabled()}))
            return 0
        if args.background and not auto_refresh_enabled():
            args.command = "show"
        if args.command == "signin":
            if not args.tool or not args.account:
                parser.error("signin needs a tool and account name")
            try:
                sign_in(args.tool, args.account)
            except accounts.AccountError as error:  # no web browser (Software offers one), or no such account
                print(str(error), file=sys.stderr)
                return 1
            return 0
        if args.command == "refresh":
            accounts.private_dir(STATE)
            inside(STATE, STATE)
            with open(STATE / ".lock", "a") as lock:
                try:
                    fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
                except BlockingIOError:
                    data = records(selected_tool=args.tool, selected_account=args.account)
                else:
                    data = records(True, args.tool, args.account, force=args.force)
        else:
            data = records(selected_tool=args.tool, selected_account=args.account)
        if args.tool:
            data = [r for r in data if r["tool"] == args.tool and (not args.account or r["account"].casefold() == args.account.casefold())]
        if legacy:
            print(json.dumps(legacy_document(data), allow_nan=False))
        elif args.json:
            print(json.dumps(data, allow_nan=False))
        else:
            for r in data:
                print(f"{r['label']} · {r['account']}" + (" · Selected for new sessions" if r["active"] else ""))
                if not accounts.binary(r["tool"]):
                    print(f"  Not installed. Open Settings > AI to set up {r['label']}.")
                    continue
                for w in r["windows"]:
                    reset = max(0, math.ceil((w["resetsAt"] - time.time()) / 60)) if w["resetsAt"] else None
                    print(f"  {w['label']}: {w['percent']:g}% used" + (f" · reset in {reset}m" if reset is not None else " · reset unknown"))
                if r["fetchedAt"]:
                    print(f"  Last good reading: {max(0, int((time.time() - r['fetchedAt']) / 60))}m ago")
                if r["authRequired"]:
                    print("  Sign-in needed. Open Settings > AI to sign in or renew this account's sign-in.")
                elif r["reason"]:
                    print("  Couldn't refresh: " + r["reason"])
                if r["note"]:
                    print("  " + r["note"])
                if r["local"]:
                    print(f"  Recorded local tokens: {r['local']['total']:,}")
                if r["localError"]:
                    print("  " + r["localError"])
        return 0
    except UsageError as error:
        if args.json:
            print(json.dumps({"ok": False, "error": str(error)}))
        else:
            print(str(error), file=sys.stderr)
        return 1
    except (accounts.AccountError, OSError, ValueError, TypeError):
        print("Couldn't read AI usage. Check the account registry and usage folder permissions.", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
