#!/usr/bin/env python3
"""Query Performance Tracker DB, calculate Team's Debt, update DB description."""
import json, urllib.request, os

NOTION_KEY = open("/home/clawd/secrets/notion/api_key").read().strip()
DB_ID = "310330c286468155b1cad36e686c559a"
HEADERS = {
    "Authorization": f"Bearer {NOTION_KEY}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json",
}

def notion_request(method, url, body=None):
    data = json.dumps(body).encode() if body else None
    req = urllib.request.Request(url, data=data, headers=HEADERS, method=method)
    return json.loads(urllib.request.urlopen(req).read())

# Query all entries
all_results = []
cursor = None
while True:
    body = {"page_size": 100}
    if cursor:
        body["start_cursor"] = cursor
    resp = notion_request("POST", f"https://api.notion.com/v1/databases/{DB_ID}/query", body)
    all_results.extend(resp["results"])
    if not resp.get("has_more"):
        break
    cursor = resp["next_cursor"]

# Calculate totals
total_wasted = sum((r["properties"]["Cost Wasted"]["number"] or 0) for r in all_results)
total_saved = sum((r["properties"]["Cost Saved"]["number"] or 0) for r in all_results)
balance = total_saved - total_wasted
incidents = len(all_results)
time_wasted = sum((r["properties"]["Time Wasted"]["number"] or 0) for r in all_results)
ideas_owed = -(-time_wasted // 15)  # ceil division

# Format
if balance >= 0:
    emoji = "🟢"
    label = "TEAM'S CREDIT"
    amount = f"+${balance:,}"
else:
    emoji = "🔴"
    label = "TEAM'S DEBT"
    amount = f"−${abs(balance):,}"

description = [
    {"type": "text", "text": {"content": f"{emoji} {label}: {amount}\n"}, "annotations": {"bold": True}},
    {"type": "text", "text": {"content": f"${total_wasted:,} wasted · ${total_saved:,} saved · {incidents} incidents · {ideas_owed} ideas owed\n"}},
    {"type": "text", "text": {"content": "Auto-calculated from all entries. $5/min @ $300/hr."}, "annotations": {"italic": True, "color": "gray"}},
]

# Update DB description
notion_request("PATCH", f"https://api.notion.com/v1/databases/{DB_ID}", {"description": description})

print(f"{emoji} {label}: {amount} | {incidents} incidents | ${total_wasted:,} wasted, ${total_saved:,} saved | {ideas_owed} ideas owed")
