"""Check a publisher invoice against its purchase order.

Restricted: it reads purchase prices and agreed discounts, so it lives in
restricted/. The file name is the permission: check_invoice. Until someone is
granted check_invoice, the brain won't run it for them.

In a real shop this would query your purchasing system, using credentials from
restricted/.env (for example SALES_DB_URL). This sample reads restricted/data/,
which the agent's own file tools cannot open.
"""
import csv
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
from agents import function_tool

DATA = Path(__file__).parent / "data"


def _rows(name: str) -> list[dict]:
    with open(DATA / name, newline="") as f:
        return list(csv.DictReader(f))


@function_tool
def check_invoice(invoice_id: str) -> dict:
    """Compare one publisher invoice with its purchase order, line by line, including agreed discounts."""
    lines = [r for r in _rows("invoices.csv") if r["invoice_id"] == invoice_id.strip().upper()]
    if not lines:
        return {"error": f"No invoice {invoice_id}."}
    order_id = lines[0]["order_id"]
    ordered = {r["title"]: r for r in _rows("orders.csv") if r["order_id"] == order_id}
    differences, over = [], Decimal("0")
    seen = set()
    for line in lines:
        seen.add(line["title"])
        agreed = ordered.get(line["title"])
        if agreed is None:
            differences.append({"title": line["title"], "problem": "not on the order"})
            continue
        invoiced_price = Decimal(line["list_price"])
        ordered_price = Decimal(agreed["list_price"])
        copies = int(line["copies"])
        ordered_copies = int(agreed["copies"])
        charged = (invoiced_price * copies * (1 - Decimal(line["discount"]))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        should = (ordered_price * ordered_copies * (1 - Decimal(agreed["agreed_discount"]))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        if copies != ordered_copies or invoiced_price != ordered_price or Decimal(line["discount"]) != Decimal(agreed["agreed_discount"]):
            differences.append({
                "title": line["title"],
                "copies": copies,
                "ordered_copies": ordered_copies,
                "invoiced_list_price": str(invoiced_price),
                "ordered_list_price": str(ordered_price),
                "invoiced_discount": f'{Decimal(line["discount"]):.0%}',
                "agreed_discount": f'{Decimal(agreed["agreed_discount"]):.0%}',
                "difference": float(charged - should),
            })
            over += charged - should
    for title in ordered.keys() - seen:
        differences.append({"title": title, "problem": "missing from invoice"})
    return {
        "invoice": invoice_id.upper(),
        "order": order_id,
        "publisher": next(iter(ordered.values()))["publisher"] if ordered else None,
        "lines_checked": len(lines),
        "differences": differences,
        "over_by": float(over),
    }
