#!/usr/bin/env python3
"""Look up appt type names."""
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"
REST_BASE = "https://pm-api-137.advancedmd.com/api"

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):
    req = Request(url, data=body.encode("utf-8"), method="POST", headers={"Content-Type":"text/xml"})
    try:
        with urlopen(req, timeout=60) as r: return r.read().decode("utf-8")
    except HTTPError as e: return e.read().decode("utf-8")
def login():
    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)
    t2 = post(f"{ws}/xmlrpc/processrequest.aspx", body)
    return re.search(r'<usercontext[^>]*?>([^<]+)</usercontext>', t2, re.IGNORECASE).group(1).strip()
token = login()
print("token OK", file=sys.stderr)
# try common appointment type lookup endpoints
for path in [
    "/scheduler/appointmenttypes",
    "/scheduler/appointmenttypes?facilityId=3197",
    "/system/appointmenttypes",
    "/scheduler/types",
    "/lookup/appointmenttypes",
]:
    req = Request(f"{REST_BASE}{path}", method="GET", headers={
        "Authorization": f"Bearer {token}",
        "Accept": "application/vnd.advancedmd.api.v2+json,application/json",
        "Referer": "https://static-100.advancedmd.com/",
    })
    try:
        with urlopen(req, timeout=30) as r:
            txt = r.read().decode("utf-8")
            print(f"=== {path} 200 len={len(txt)}", file=sys.stderr)
            print(txt[:6000])
            print("---")
    except HTTPError as e:
        print(f"=== {path} {e.code}", file=sys.stderr)
