#!/usr/bin/env python3
"""Login via XMLRPC, then try the REST scheduler endpoint."""
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]
OFFICE = CREDS["office_key"]
USER = api_user["user"]
PSW = api_user["password"]
APP = api_user.get("appname", "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, ct="text/xml", headers=None):
    h = {"Content-Type": ct}
    if headers: h.update(headers)
    req = Request(url, data=body.encode("utf-8") if isinstance(body,str) else body, method="POST", headers=h)
    try:
        with urlopen(req, timeout=60) as r: return r.read().decode("utf-8"), r.status
    except HTTPError as e: return e.read().decode("utf-8"), e.code

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:", token, file=sys.stderr)
print("WS:", ws, file=sys.stderr)

# Try REST against pm-api-137 with this token
def get(url):
    req = Request(url, 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: return r.read().decode("utf-8"), r.status
    except HTTPError as e: return e.read().decode("utf-8"), e.code

for base in ["https://pm-api-137.advancedmd.com/api","https://ow2-pm-api-137.igw.advancedmd.com/api"]:
    body, st = get(f"{base}/scheduler/columns")
    print(f"=== {base}/scheduler/columns -> {st} len {len(body)}", file=sys.stderr)
    if st == 200:
        print(body[:5000])
        break
    print(body[:400], file=sys.stderr)
