"""Validated tools and a durable synthetic refund ledger. Python 3.10+, stdlib.
Save locally; python week10.py --lesson 1|2|3|all. No real money or network.
Temporary files only. Exceptions represent explicit contract outcomes.
"""
import argparse
import asyncio
import hashlib
import json
import sqlite3
import tempfile
from pathlib import Path


class ToolError(Exception):
    pass


def fail(condition, message):
    if not condition:
        raise ToolError(message)


def dispatch(name, args, actor, root):
    fail(name in {"search_files", "lookup", "arithmetic", "broken"}, "unknown_tool")
    fail(type(args) is dict, "arguments_not_object")
    fail("read" in actor["permissions"], "denied")
    if name == "search_files":
        fail(set(args) == {"query", "limit"}, "unexpected_or_missing_field")
        fail(type(args["query"]) is str and 0 < len(args["query"]) <= 80, "bad_query")
        fail(type(args["limit"]) is int and 1 <= args["limit"] <= 5, "bad_limit")
        matches = []
        for path in sorted(root.glob("*.txt")):
            # The exercise root is executor configuration, never an argument.
            if args["query"].lower() in path.read_text(encoding="utf-8").lower():
                matches.append(path.name)
        result = {"status": "ok", "value": matches[:args["limit"]]}
    elif name == "lookup":
        fail(set(args) == {"service"} and type(args["service"]) is str, "bad_arguments")
        values = {"mail": "healthy", "storage": "degraded"}
        result = {"status": "ok", "value": values[args["service"]]} if args["service"] in values else {"status": "not_found", "value": None}
    elif name == "arithmetic":
        fail(set(args) == {"operation", "left", "right"}, "bad_arguments")
        fail(args["operation"] in {"add", "subtract", "multiply"}, "bad_operation")
        fail(all(type(args[k]) is int and abs(args[k]) <= 1000 for k in ("left", "right")), "bad_operand")
        a, b = args["left"], args["right"]
        operations = {"add": lambda: a+b, "subtract": lambda: a-b, "multiply": lambda: a*b}
        result = {"status": "ok", "value": operations[args["operation"]]()}
    else:
        result = "Traceback: deliberately malformed output"
    fail(type(result) is dict and set(result) == {"status", "value"}, "malformed_output")
    fail(result["status"] in {"ok", "not_found"}, "malformed_output")
    if name == "search_files":
        fail(type(result["value"]) is list and all(type(x) is str for x in result["value"]), "malformed_output")
    if name == "arithmetic":
        fail(type(result["value"]) is int, "malformed_output")
    if name == "lookup":
        fail((result["status"] == "ok" and type(result["value"]) is str) or
             (result["status"] == "not_found" and result["value"] is None), "malformed_output")
    return result


def expect_error(function, category):
    try:
        function()
    except ToolError as error:
        assert str(error) == category, (str(error), category)
        return
    raise AssertionError(f"expected {category}")


def lesson1(folder):
    root = Path(folder) / "docs"
    root.mkdir()
    (root / "reset.txt").write_text("Staff reset passwords online.", encoding="utf-8")
    actor = {"id": "lee", "permissions": {"read"}}
    assert dispatch("search_files", {"query": "reset", "limit": 2}, actor, root)["value"] == ["reset.txt"]
    assert dispatch("lookup", {"service": "mail"}, actor, root)["value"] == "healthy"
    assert dispatch("arithmetic", {"operation": "multiply", "left": 6, "right": 7}, actor, root)["value"] == 42
    expect_error(lambda: dispatch("unknown", {}, actor, root), "unknown_tool")
    expect_error(lambda: dispatch("search_files", {"query": "reset", "limit": True}, actor, root), "bad_limit")
    expect_error(lambda: dispatch("lookup", {"service": "mail", "owner": "admin"}, actor, root), "bad_arguments")
    expect_error(lambda: dispatch("arithmetic", {"operation": "eval", "left": 1, "right": 2}, actor, root), "bad_operation")
    expect_error(lambda: dispatch("broken", {}, actor, root), "malformed_output")
    print("PASS lesson 1: three real local tools; unknown, malformed, forged identity, eval, and output guards")


def database(path):
    db = sqlite3.connect(path)
    db.execute("CREATE TABLE IF NOT EXISTS operations (key TEXT PRIMARY KEY, owner TEXT, fingerprint TEXT, status TEXT, result TEXT)")
    db.execute("CREATE TABLE IF NOT EXISTS refunds (key TEXT PRIMARY KEY, owner TEXT, cents INTEGER, destination TEXT)")
    return db


def fingerprint(action):
    return hashlib.sha256(json.dumps(action, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


def refund(db, key, action, actor, approval, now=100):
    fail("refund" in actor["permissions"], "denied")
    fail(set(action) == {"order", "cents", "destination", "owner"}, "bad_arguments")
    fail(action["owner"] == actor["id"], "denied")
    fail(type(action["cents"]) is int and 0 < action["cents"] <= 1000, "bad_amount")
    digest = fingerprint(action)
    # A single write transaction serializes read-deduplicate-insert in this local store.
    db.execute("BEGIN IMMEDIATE")
    try:
        existing = db.execute("SELECT owner,fingerprint,status,result FROM operations WHERE key=?", (key,)).fetchone()
        if existing:
            fail(existing[0] == actor["id"], "denied")
            fail(existing[1] == digest, "idempotency_conflict")
            result = json.loads(existing[3])
            db.commit()
            return result
        fail(approval["owner"] == actor["id"] and approval["fingerprint"] == digest and approval["expires"] > now, "approval_mismatch")
        already = db.execute("SELECT COALESCE(SUM(cents),0) FROM refunds WHERE owner=?", (actor["id"],)).fetchone()[0]
        fail(already + action["cents"] <= 1000, "remaining_balance")
        result = {"status": "committed", "key": key, "cents": action["cents"]}
        db.execute("INSERT INTO refunds VALUES (?,?,?,?)", (key, actor["id"], action["cents"], action["destination"]))
        db.execute("INSERT INTO operations VALUES (?,?,?,?,?)", (key, actor["id"], digest, "committed", json.dumps(result)))
        db.commit()
        return result
    except Exception:
        db.rollback()
        raise


def status(db, key, actor):
    fail("read" in actor["permissions"], "denied")
    row = db.execute("SELECT owner,result FROM operations WHERE key=?", (key,)).fetchone()
    if row is None:
        return {"status": "not_found"}
    fail(row[0] == actor["id"], "denied")
    return json.loads(row[1])


def fixture():
    action = {"order": "O7", "cents": 300, "destination": "original", "owner": "lee"}
    actor = {"id": "lee", "permissions": {"read", "refund"}}
    approval = {"owner": "lee", "fingerprint": fingerprint(action), "expires": 200}
    return action, actor, approval


async def async_cases(path):
    db = database(path)
    action, actor, approval = fixture()
    async def lost_response():
        await asyncio.sleep(0)
        refund(db, "refund-8", action, actor, approval)
        # Deliberate transport simulation AFTER commit, not a real network claim.
        raise TimeoutError("simulated response lost after commit")
    try:
        await lost_response()
        raise AssertionError("expected simulated timeout")
    except TimeoutError:
        pass
    assert status(db, "refund-8", actor)["status"] == "committed"
    assert refund(db, "refund-8", action, actor, approval)["cents"] == 300
    assert db.execute("SELECT COUNT(*) FROM refunds").fetchone()[0] == 1
    started = asyncio.Event()
    gate = asyncio.Event()
    effects = []
    async def queued():
        started.set()
        await gate.wait()
        effects.append("sent")
    task = asyncio.create_task(queued())
    await started.wait()
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        pass
    assert task.cancelled() and effects == []
    db.close()
    print("PASS lesson 2: awaited execution, postcommit response loss reconciled, same-key retry, cancellation before effect")


def lesson2(folder):
    asyncio.run(async_cases(Path(folder) / "async.sqlite"))


def lesson3(folder):
    path = Path(folder) / "ledger.sqlite"
    db = database(path)
    action, actor, approval = fixture()
    first = refund(db, "refund-31", action, actor, approval)
    db.close()
    db = database(path)
    assert refund(db, "refund-31", action, actor, approval) == first
    changed_amount = {**action, "cents": 700}
    expect_error(lambda: refund(db, "refund-31", changed_amount, actor, approval), "idempotency_conflict")
    changed_destination = {**action, "destination": "external"}
    expect_error(lambda: refund(db, "new-key", changed_destination, actor, approval), "approval_mismatch")
    expect_error(lambda: refund(db, "expired", action, actor, approval, now=201), "approval_mismatch")
    viewer = {"id": "lee", "permissions": {"read"}}
    expect_error(lambda: refund(db, "refund-31", action, viewer, approval), "denied")
    stranger = {"id": "quinn", "permissions": {"read", "refund"}}
    expect_error(lambda: status(db, "refund-31", stranger), "denied")
    assert db.execute("SELECT COUNT(*),SUM(cents) FROM refunds").fetchone() == (1, 300)
    db.close()
    print("PASS lesson 3: restart deduplication; changed amount, destination, expiry, caller, and result access denied")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--lesson", choices=["1", "2", "3", "all"], default="all")
    args = parser.parse_args()
    with tempfile.TemporaryDirectory(prefix="academy-tools-") as folder:
        for number, function in enumerate((lesson1, lesson2, lesson3), 1):
            if args.lesson in (str(number), "all"):
                function(folder)


if __name__ == "__main__":
    main()
