#!/usr/bin/env python3
"""Probe getdatevisits with apptstatus and duration."""
import json, re, sys
from datetime import datetime
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError

CREDS_PATH = Path("/Users/exult/claude-workspace/config/credentials/advancedmd.json")
with open(CREDS_PATH) as f:
    creds = json.load(f)
api_user = creds["api_users"][0]
OFFICE_KEY = creds["office_key"]
USERNAME = api_user["user"]
PASSWORD = api_user["password"]
APPNAME = api_user.get("appname", "ABS-AVMD")
PARTNER_LOGIN_URL = "https://partnerlogin.advancedmd.com/practicemanager/xmlrpc/processrequest.aspx"

def now_str():
    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_xml(url, body, token=None):
    headers = {"Content-Type": "text/xml"}
    if token:
        headers["Cookie"] = f"token={token}"
    req = Request(url, data=body.encode("utf-8"), headers=headers, method="POST")
    try:
        with urlopen(req, timeout=60) as resp:
            return resp.read().decode("utf-8"), resp.status
    except HTTPError as e:
        return e.read().decode("utf-8"), e.code

body = (f'<ppmdmsg action="login" class="login" msgtime="{esc(now_str())}" '
        f'username="{esc(USERNAME)}" psw="{esc(PASSWORD)}" '
        f'officecode="{esc(OFFICE_KEY)}" appname="{esc(APPNAME)}"/>')
text1, _ = post_xml(PARTNER_LOGIN_URL, body)
ws = re.search(r'webserver="([^"]+)"', text1)
webserver = ws.group(1) if ws else None
api_url = f"{webserver}/xmlrpc/processrequest.aspx"
text2, _ = post_xml(api_url, body)
tm = re.search(r'<usercontext[^>]*?>([^<]+)</usercontext>', text2, re.IGNORECASE | re.DOTALL)
token = tm.group(1).strip()

date_arg = sys.argv[1] if len(sys.argv) > 1 else "2026-06-15"
# Add apptstatus and duration (both in AMD docs sample)
body = (f'<ppmdmsg action="getdatevisits" class="api" msgtime="{esc(now_str())}" '
        f'visitdate="{date_arg}">'
        f'<visit columnheading="ColumnHeading" duration="Duration" color="Color" apptstatus="ApptStatus"/>'
        f'<patient name="Name"/></ppmdmsg>')
text, status = post_xml(api_url, body, token)
print("STATUS=", status, file=sys.stderr)
print(text[:8000])
