"""Local read-only dispatcher exercise; no model, network or authentication."""
import argparse
import json
from pathlib import Path
import sys

from jsonschema import Draft202012Validator

ROOT = Path(__file__).resolve().parent
MAX_BYTES = 16384
MAX_CALLS = 4
CALL_SCHEMA = {
    "type": "object", "additionalProperties": False,
    "required": ["id", "name", "arguments"],
    "properties": {
        "id": {"type": "string", "pattern": "^[a-zA-Z0-9_-]{1,48}$"},
        "name": {"type": "string", "minLength": 1, "maxLength": 64},
        "arguments": {"type": "object"},
    },
}
INPUT_SCHEMA = {
    "type": "object", "additionalProperties": False, "required": ["order_id"],
    "properties": {"order_id": {"type": "string", "pattern": "^DEMO-[0-9]{4}$"}},
}
OUTPUT_SCHEMA = {
    "type": "object", "additionalProperties": False,
    "required": ["order_id", "status"],
    "properties": {
        "order_id": {"type": "string", "pattern": "^DEMO-[0-9]{4}$"},
        "status": {"enum": ["processing", "delivered", "cancelled"]},
    },
}
for _schema in (CALL_SCHEMA, INPUT_SCHEMA, OUTPUT_SCHEMA):
    Draft202012Validator.check_schema(_schema)
CALL_VALIDATOR = Draft202012Validator(CALL_SCHEMA)
INPUT_VALIDATOR = Draft202012Validator(INPUT_SCHEMA)
OUTPUT_VALIDATOR = Draft202012Validator(OUTPUT_SCHEMA)

# Aliases are deliberately local fixtures, not authenticated identities.
ACTORS = {
    "alice": {"tenant": "demo", "user": "user-a", "can_read_orders": True},
    "bob": {"tenant": "demo", "user": "user-b", "can_read_orders": True},
    "other": {"tenant": "other", "user": "user-a", "can_read_orders": True},
    "viewer": {"tenant": "demo", "user": "user-a", "can_read_orders": False},
}


class InputError(ValueError):
    pass


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise InputError("duplicate_json_key")
        result[key] = value
    return result


def reject_constant(value):
    raise InputError("non_json_constant")


def parse_calls(raw):
    if len(raw) > MAX_BYTES:
        raise InputError("input_too_large")
    try:
        value = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object,
                           parse_constant=reject_constant)
    except (UnicodeDecodeError, json.JSONDecodeError, RecursionError) as exc:
        raise InputError("invalid_json") from exc
    if not isinstance(value, list) or len(value) > 8:
        raise InputError("expected_array_up_to_eight")
    return value


def read_orders():
    return json.loads((ROOT / "orders.json").read_text(encoding="utf-8"))


def get_order_status(arguments, actor):
    for row in read_orders():
        if (row["order_id"] == arguments["order_id"] and
                row["tenant"] == actor["tenant"] and row["user"] == actor["user"]):
            return {"order_id": row["order_id"], "status": row["status"]}
    return None


REGISTRY = {"get_order_status": get_order_status}


def dispatch(calls, actor_alias, enabled=True):
    if actor_alias not in ACTORS:
        raise InputError("unknown_demo_actor")
    if not isinstance(calls, list) or len(calls) > 8:
        raise InputError("expected_array_up_to_eight")
    actor = ACTORS[actor_alias]
    results, audit, seen = [], [], set()
    invocations = 0
    for index, call in enumerate(calls):
        if index >= MAX_CALLS:
            audit.append({"index": index, "decision": "blocked", "code": "call_limit"})
            break
        call_id = None
        code, result = None, None
        if not CALL_VALIDATOR.is_valid(call):
            code = "invalid_envelope"
        else:
            call_id = call["id"]
            if call_id in seen:
                code = "duplicate_call_id"
            else:
                seen.add(call_id)
                if call["name"] not in REGISTRY:
                    code = "unknown_tool"
                elif not enabled:
                    code = "tool_disabled"
                elif not INPUT_VALIDATOR.is_valid(call["arguments"]):
                    code = "invalid_arguments"
                elif not actor["can_read_orders"]:
                    code = "permission_denied"
                else:
                    invocations += 1
                    try:
                        result = REGISTRY[call["name"]](call["arguments"], actor)
                        if result is None:
                            code = "not_available"
                        elif not OUTPUT_VALIDATOR.is_valid(result):
                            code, result = "invalid_result", None
                    except (OSError, ValueError, KeyError, TypeError):
                        code, result = "tool_failed", None
        success = code is None
        results.append({"id": call_id, "ok": success,
                        "result": result if success else None, "error": code})
        audit.append({"index": index, "id": call_id,
                      "decision": "completed" if success else "rejected", "code": code})
    return {"actor_fixture": actor_alias, "results": results, "audit": audit,
            "executor_invocations": invocations, "max_calls": MAX_CALLS,
            "limit_reached": len(calls) > MAX_CALLS, "real_model_calls": 0,
            "external_writes": 0, "authenticated": False}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("calls", type=Path)
    parser.add_argument("--actor", choices=ACTORS, default="alice")
    parser.add_argument("--disable-tool", action="store_true")
    args = parser.parse_args()
    try:
        with args.calls.open("rb") as source:
            raw = source.read(MAX_BYTES + 1)
        report = dispatch(parse_calls(raw), args.actor, not args.disable_tool)
    except (InputError, OSError) as error:
        code = str(error) if isinstance(error, InputError) else "input_file_error"
        print(json.dumps({"ok": False, "error": code}, ensure_ascii=False))
        return 2
    print(json.dumps(report, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    raise SystemExit(main())
