"""Worked solution: inspect after an attempt. Not production auth or a live model."""
import copy

def parse_request(value):
    if not isinstance(value, dict) or set(value) != {"id"}:
        return None
    if not isinstance(value["id"], str) or not value["id"].strip():
        return None
    return {"id": value["id"]}

def validate_answer(envelope, source):
    if not isinstance(envelope, dict) or envelope.get("status") != "ok":
        return False
    payload = envelope.get("payload")
    if not isinstance(payload, dict) or set(payload) != {"id", "time"}:
        return False
    if any(not isinstance(payload[k], str) or not payload[k].strip() for k in payload):
        return False
    return payload["id"] == source["id"] and payload["time"] == source["time"]

def lookup(caller, request, records):
    value = parse_request(request)
    if value is None:
        return {"status": "invalid"}
    record = records.get(value["id"])
    if record is None:
        return {"status": "missing"}
    if record["scope"] != "public" and caller != "staff":
        return {"status": "denied"}
    return {"status": "ok", "record": dict(record)}

def once(operation_id, operation, cache):
    if operation_id not in cache:
        cache[operation_id] = operation()
    return cache[operation_id]

def run(caller, request, records, operation_id, cache):
    if not isinstance(operation_id, str) or not operation_id.strip() or not isinstance(cache, dict):
        return {"status": "invalid"}
    result = lookup(caller, request, records)
    if result["status"] != "ok":
        return {"status": result["status"]}
    record = result["record"]
    # Reauthorize every read before cache reuse. Bind the exercise's cached
    # artifact to actor, exact request and current trusted source contents.
    intent = {"caller": caller, "id": record["id"], "time": record["time"], "scope": record["scope"]}
    key = ("run", operation_id)
    if key in cache and cache[key]["intent"] != intent:
        return {"status": "key_conflict"}
    def operation():
        envelope = {"status": "ok", "payload": {"id": record["id"], "time": record["time"]}}
        answer = {"status": "ok", "artifact": dict(envelope["payload"])} if validate_answer(envelope, record) else {"status": "unsupported"}
        return {"intent": intent, "result": answer}
    return copy.deepcopy(once(key, operation, cache)["result"])
