#!/usr/bin/env python3
"""Fetch AMD appt type names via XMLRPC getappttypes."""
import json, re, sys
from datetime import datetime
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError

CREDS = json.loads(Path("/Users/exult/claude-workspace/config/credentials/advancedmd.json").read_text())
api_user = CREDS["api_users"][0]
USER = api_user["user"]; PSW = api_user["password"]; OFFICE = CREDS["office_key"]; APP = "ABS-AVMD"
PARTNER = "https://partnerlogin.advancedmd.com/practicemanager/xmlrpc/processrequest.aspx"

def now(): return datetime.now().strftime("%m/%d/%Y %I:%M:%S %p")
def esc(s): return s.replace("&","&amp;").replace("<","&lt;").replace(">","&gt;").replace('"',"&quot;").replace("'","&apos;")
def post(url, body, token=None):
    headers={"Content-Type":"text/xml"}
    if token: headers["Cookie"] = f"token={token}"
    req = Request(url, data=body.encode("utf-8"), method="POST", headers=headers)
    try:
        with urlopen(req, timeout=60) as r: return r.read().decode("utf-8")
    except HTTPError as e: return e.read().decode("utf-8")

body = (f'<ppmdmsg action="login" class="login" msgtime="{esc(now())}" '
        f'username="{esc(USER)}" psw="{esc(PSW)}" '
        f'officecode="{esc(OFFICE)}" appname="{esc(APP)}"/>')
t1 = post(PARTNER, body); ws = re.search(r'webserver="([^"]+)"', t1).group(1)
api_url = f"{ws}/xmlrpc/processrequest.aspx"
t2 = post(api_url, body)
token = re.search(r'<usercontext[^>]*?>([^<]+)</usercontext>', t2, re.IGNORECASE).group(1).strip()
print("token len", len(token), file=sys.stderr)

# call getappttypes
body = (f'<ppmdmsg action="getappttypes" class="masterfiles" msgtime="{esc(now())}"><appttype/></ppmdmsg>')
resp = post(api_url, body, token)
# Find all appttype id="" name=""
matches = re.findall(r'<appttype\s+id="([^"]+)"\s+name="([^"]+)"', resp)
print(f"Found {len(matches)} appt types", file=sys.stderr)
mapping = {}
for tid, name in matches:
    # IDs are like 'ap_type11' — strip prefix
    m = re.match(r'ap_type(\d+)', tid)
    if m: mapping[int(m.group(1))] = name
    else: mapping[tid] = name

# Focus on the IDs we care about
INTEREST = [6614, 6609, 6608, 6611, 6613, 6610, 7014, 7023, 6606, 6605]
print("\n=== APPT TYPES OF INTEREST ===", file=sys.stderr)
for tid in INTEREST:
    print(f"  {tid}: {mapping.get(tid, '<not found>')}")

# Dump all (top 60) for context
print("\n=== ALL APPT TYPES (id sorted) ===")
for tid in sorted(mapping.keys(), key=lambda x: x if isinstance(x,int) else 0):
    print(f"  {tid}: {mapping[tid]}")

Path("/tmp/amd-appttypes.json").write_text(json.dumps(mapping, indent=2, default=str))
