import json, sys, datetime as dt
RULES = {
    "open_periods": {"2026-10"},
    "allowed_accounts": {"6210000", "6280000", "6290000", "4100000", "4800000", "4850000"},
    "auto_limit": 5000.00,          # above this, a named person must approve
    "required": ["proposal_id", "date", "period", "description", "source_documents", "lines"],
}

def check(p):
    errors, warnings = [], []
    for f in RULES["required"]:
        if not p.get(f): errors.append(f"missing field: {f}")
    if errors: return errors, warnings
    if p["period"] not in RULES["open_periods"]: errors.append(f"period {p['period']} is not open")
    if p["date"][:7] != p["period"]: errors.append("date outside the period")
    dr = round(sum(l.get("debit", 0) for l in p["lines"]), 2)
    cr = round(sum(l.get("credit", 0) for l in p["lines"]), 2)
    if dr != cr: errors.append(f"not balanced: debit {dr} vs credit {cr}")
    for i, l in enumerate(p["lines"], 1):
        if l["account"] not in RULES["allowed_accounts"]: errors.append(f"line {i}: account {l['account']} not allowed for this agent")
        if l.get("debit", 0) and l.get("credit", 0): errors.append(f"line {i}: debit and credit on the same line")
        if l.get("debit", 0) < 0 or l.get("credit", 0) < 0: errors.append(f"line {i}: negative amount")
    if p.get("status") != "draft": errors.append("status must be 'draft'")
    if dr > RULES["auto_limit"]: warnings.append(f"amount {dr} above {RULES['auto_limit']}: route to a named approver")
    return errors, warnings

for path in sys.argv[1:]:
    e, w = check(json.load(open(path, encoding="utf-8")))
    print(path, "REJECTED" if e else "ACCEPTED AS DRAFT", e + w)
