"""Usage: python reconcile_agent.py [invoices.xlsx payouts.xlsx]. One currency; integer cents."""
import json
from pathlib import Path
import sys

from openpyxl import Workbook, load_workbook

from agent_tools import ask, execute, workspace

SAMPLES = [
    [["Invoice ID", "Invoice cents"], ["001", 12500], ["002", 9000],
     ["003", 4000], ["004", 1000], ["004", 1000]],
    [["Reference", "Paid cents"], ["001", 12500], ["002", 8500], ["005", 2000]],
]
COMPARE = """import json
from collections import defaultdict
from pathlib import Path

def group(name):
    result = defaultdict(list)
    for reference, cents in json.loads(Path(name).read_text()):
        result[reference].append(cents)
    return result

invoices, payouts = group('invoices.json'), group('payouts.json')
for key in sorted(invoices.keys() | payouts.keys()):
    left, right = invoices[key], payouts[key]
    if len(left) > 1 or len(right) > 1:
        reason = 'duplicate reference'
    elif not left:
        reason = 'payout only'
    elif not right:
        reason = 'invoice only'
    elif left != right:
        reason = 'amount mismatch'
    else:
        continue
    print(json.dumps([key, reason, str(left), str(right)]))
"""


def normalize(rows):
    headers, *values = rows
    if len(set(headers)) != len(headers) or not all(isinstance(h, str) for h in headers):
        raise ValueError("Use distinct text column headers")
    mapping = ask(f"These Excel headers are {headers!r}. Return JSON with keys reference "
                  "and cents, mapped to the exact reference ID and integer cents column names.")
    ref, amount = (headers.index(mapping[key]) for key in ("reference", "cents"))
    if ref == amount:
        raise ValueError("Reference and amount need separate columns")
    pairs = []
    for row in values:
        if all(value is None for value in row):
            continue
        if not isinstance(row[ref], str) or not row[ref].strip() or type(row[amount]) is not int:
            raise ValueError("Use text references and integer cents. Check blank cells and formulas.")
        pairs.append([row[ref].strip(), row[amount]])
    return pairs


def read_rows(path):
    book = load_workbook(path, read_only=True, data_only=False)
    try:
        return list(book.active.values)
    finally:
        book.close()


if __name__ == "__main__":
    if len(sys.argv) not in (1, 3):
        sys.exit(__doc__)
    inputs = [read_rows(p) for p in sys.argv[1:]] or SAMPLES
    report = Workbook()
    sheet = report.active
    sheet.title = "Exceptions"
    sheet.append(["Reference", "Reason", "Invoice amounts (cents)", "Payout amounts (cents)"])
    with workspace(block_network=True) as box:
        for name, rows in zip(("invoices", "payouts"), inputs):
            box.filesystem.write_text(json.dumps(normalize(rows)), f"/work/{name}.json")
        lines = execute(box, "python3", "-c", COMPARE).splitlines()
    for line in lines:
        sheet.append(json.loads(line))
        for cell in sheet[sheet.max_row]:
            cell.data_type = "s"
    report.save("exceptions.xlsx")
    print(f"Wrote {len(lines)} exceptions to exceptions.xlsx")
