#!/usr/bin/env python3
"""One-shot PO header speed macro for Michel demo calibration.
Creates a minimal demo PO header using the currently mapped Purchase Order Maintenance screen.
Coordinates assume 1600x1200 MCSJ window and current PO Maintenance screen.
"""
import ctypes, json, time
from pathlib import Path

import pyperclip
import pyautogui

pyautogui.FAILSAFE = False
pyautogui.PAUSE = 0.08

user32 = ctypes.WinDLL('user32', use_last_error=True)

ROOT = Path(r"C:\MCSJAgent\proof\MichelBridge")
ROOT.mkdir(parents=True, exist_ok=True)

def click(x,y, wait=.35):
    pyautogui.click(x,y)
    time.sleep(wait)

def paste(text, wait=.25):
    pyperclip.copy(text)
    pyautogui.hotkey('ctrl','v')
    time.sleep(wait)

def shot(path):
    im = pyautogui.screenshot()
    im.save(path)
    return {'path': str(path), 'width': im.width, 'height': im.height}

def main():
    desc = 'MICHEL_FAST_TEST_' + time.strftime('%H%M%S')
    start = time.perf_counter()
    proof = {}

    # Current mapped screen should be saved PO Maintenance with Add visible.
    proof['before'] = shot(ROOT / ('po-speed-before-' + time.strftime('%Y%m%d-%H%M%S') + '.png'))

    # Add -> Select Prefix OK -> Add Record OK.
    click(60,235, .8)       # Add
    click(522,586, .8)      # Select Prefix OK
    click(560,592, 1.4)     # Add Record OK

    # Fill minimal header fields. Vendor and Description are anchored by coordinates; data entry is clipboard paste.
    click(600,315,.2)       # Vendor field
    paste('SACCH005', .4)
    click(185,405,.2)       # Description field
    paste(desc, .4)

    # Save and confirm.
    click(130,235, .9)      # Save
    click(518,627, 2.5)     # Yes in save confirmation

    elapsed = time.perf_counter() - start
    proof['after'] = shot(ROOT / ('po-speed-after-' + time.strftime('%Y%m%d-%H%M%S') + '.png'))
    print(json.dumps({'ok': True, 'description': desc, 'elapsed_seconds': round(elapsed,2), 'proof': proof}, separators=(',', ':')))

if __name__ == '__main__':
    main()
