"""Set billout_rate_usd on Adi + Gary and backfill billout_amount_usd
on every existing entry whose team_member has a rate set."""
import json, os, re, urllib.request
from pathlib import Path

def load_env():
    for line in Path('/srv/apps/work/.env').read_text().splitlines():
        m = re.match(r'^([A-Z_]+)\s*=\s*(.*)$', line.strip())
        if m: os.environ.setdefault(m.group(1), m.group(2).strip().strip('"').strip("'"))

load_env()
BASE = os.environ['NEXT_PUBLIC_SUPABASE_URL'].rstrip('/') + '/rest/v1'
HDRS = {
    'apikey': os.environ['SUPABASE_SECRET_KEY'],
    'Authorization': 'Bearer ' + os.environ['SUPABASE_SECRET_KEY'],
    'Content-Type': 'application/json',
}

def req(method, path, payload=None, prefer=None):
    headers = {**HDRS}
    if prefer: headers['Prefer'] = prefer
    r = urllib.request.Request(
        BASE + '/' + path,
        data=json.dumps(payload).encode() if payload is not None else None,
        headers=headers, method=method,
    )
    with urllib.request.urlopen(r) as resp:
        body = resp.read().decode()
        return json.loads(body) if body else None, resp.headers.get('Content-Range')

# 1. Set Adi + Gary billout_rate_usd = 25.
for email in ('info@adipramono.com', 'gary@rian.ca'):
    data, _ = req(
        'PATCH',
        f'team_members?email=eq.{email}',
        {'billout_rate_usd': 25},
        prefer='return=representation',
    )
    for d in data or []:
        print(f"set {d['display_name']!r:24s} ({d['email']:24s}) → billout_rate_usd = ${d['billout_rate_usd']}")

# 2. Backfill billout_amount_usd on every time_entry whose team_member has a rate.
#    Two-step: load all rated team_members, then update entries per member.
members, _ = req(
    'GET',
    'team_members?select=id,display_name,billout_rate_usd&billout_rate_usd=not.is.null',
)
print(f'\nteam_members with billout_rate set: {len(members)}')
for m in members:
    rate = float(m['billout_rate_usd'])
    # Pull every entry for this team_member that has converted_duration_seconds.
    entries, _ = req(
        'GET',
        f'time_entries?select=id,converted_duration_seconds&team_member_id=eq.{m["id"]}'
        f'&converted_duration_seconds=not.is.null&limit=10000',
    )
    print(f"  {m['display_name']:24s} @ ${rate}/hr — {len(entries)} entries to backfill")
    updated = 0
    for e in entries:
        secs = e.get('converted_duration_seconds')
        if secs is None: continue
        amount = round((secs / 3600) * rate * 100) / 100  # 2dp like the cost column
        _, _ = req('PATCH', f'time_entries?id=eq.{e["id"]}', {'billout_amount_usd': amount}, prefer='return=minimal')
        updated += 1
    print(f"    updated {updated}")

print('\nDone.')
