#!/usr/bin/env python3
"""Create a training PO with realistic header comment and 3 line items.
Runs inside the interactive Windows desktop session. Business-facing fields must use realistic procurement wording.
"""
import ctypes, json, time
from pathlib import Path

import pyautogui
import pyperclip

pyautogui.FAILSAFE = False
pyautogui.PAUSE = 0.05
ROOT = Path(r"C:\MCSJAgent\proof\MichelBridge")
ROOT.mkdir(parents=True, exist_ok=True)

DESC = "Public works field supplies"
HEADER_COMMENT = "Deliver to DPW receiving area; match invoice to packing slip and notify purchasing before substitutions."
ACCOUNT_ROW = (610, 317)   # visible F-1910-0400 CONTRACTUAL EXPENSE row in account picklist
ACCOUNT_OK = (663, 654)


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


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


def select_all_paste(text, wait=0.2):
    pyautogui.hotkey('ctrl', 'a')
    time.sleep(0.05)
    paste(text, wait)


def shot(label):
    path = ROOT / f"full-po-{label}-{time.strftime('%Y%m%d-%H%M%S')}.png"
    im = pyautogui.screenshot()
    im.save(path)
    return {"path": str(path), "width": im.width, "height": im.height}


def save_yes(wait=1.0):
    click(130, 225, 0.65)   # Save
    click(482, 620, wait)   # Yes in save confirmation


def fill_line(seq, desc, price, choose_account=False):
    # Add a new line. For seq>1 duplicate previous then overwrite desc/price.
    click(60, 225, 0.55)        # Add
    if seq == 1:
        click(802, 633, 0.9)    # Add Line Item OK, leave duplicate unchecked
        # Description
        click(175, 462, 0.1); select_all_paste(desc, 0.15)
        # Charge account via picklist: F-1910-0400 CONTRACTUAL EXPENSE
        click(675, 493, 0.55)
        click(*ACCOUNT_ROW, wait=0.1)
        click(*ACCOUNT_OK, wait=0.55)
        # Unit price
        click(145, 705, 0.1); select_all_paste(price, 0.15)
    else:
        click(690, 570, 0.08)   # duplicate previous checkbox
        click(802, 633, 0.75)   # OK
        click(175, 462, 0.1); select_all_paste(desc, 0.15)
        click(145, 705, 0.1); select_all_paste(price, 0.15)
    save_yes(1.0)


def main():
    start = time.perf_counter()
    proof = {"before": shot("before")}

    # Header: assumes Purchase Order Maintenance with an existing saved PO visible.
    click(60, 235, 0.65)       # Add
    click(522, 586, 0.65)      # Select Prefix OK
    click(560, 592, 1.1)       # Add Record OK
    click(600, 315, 0.1); paste('SACCH005', 0.25)
    click(185, 405, 0.1); paste(DESC, 0.25)
    click(660, 600, 0.1); paste(HEADER_COMMENT, 0.25)
    save_yes(1.25)
    proof["header_saved"] = shot("header-saved")

    # Line item window.
    click(755, 225, 0.9)       # LineItem button
    fill_line(1, "Field repair supplies", "0.01")
    fill_line(2, "Permit office materials", "0.02")
    fill_line(3, "Maintenance replacement parts", "0.03")
    proof["line3_saved"] = shot("line3-saved")

    # Close line item window back to header, preserving saved lines.
    click(250, 225, 0.8)       # Close
    proof["final_header"] = shot("final-header")

    elapsed = time.perf_counter() - start
    print(json.dumps({
        "ok": True,
        "description": DESC,
        "header_comment": HEADER_COMMENT,
        "line_descriptions": ["Field repair supplies", "Permit office materials", "Maintenance replacement parts"],
        "line_prices": ["0.01", "0.02", "0.03"],
        "elapsed_seconds": round(elapsed, 2),
        "proof": proof,
    }, separators=(",", ":")))


if __name__ == "__main__":
    main()
