"""Bounded agent runtime, Python 3.10+ standard library.
Save locally; python week09.py --lesson 1|2|3|all.
Optional real local model: --model-url http://localhost:1234/v1/chat/completions
--model YOUR_MODEL. Requires your already running compatible local endpoint.
Core checks use scripted proposals; these do not measure a language model.
"""
import argparse
import json
import time
import urllib.parse
import urllib.request

SERVICES = {"mail": "healthy", "storage": "degraded", "dns": "healthy"}


def validate_local_url(url):
    parsed = urllib.parse.urlsplit(url)
    if (parsed.scheme != "http" or parsed.hostname not in {"localhost", "127.0.0.1", "::1"}
            or parsed.username is not None or parsed.password is not None
            or parsed.port is None or not 1 <= parsed.port <= 65535 or parsed.fragment):
        raise ValueError("use an explicit loopback HTTP endpoint without user information or fragments")
    return url


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise ValueError("optional local endpoint redirects are not allowed")


def lookup(service):
    if service == "timeout":
        return {"status": "timeout"}
    if service not in SERVICES:
        return {"status": "not_found"}
    return {"status": "ok", "value": SERVICES[service]}


def scripted(state):
    if any(o["status"] == "ok" for o in state["observations"]):
        return {"action": "finish"}
    return {"action": "lookup", "service": state["service"]}


def run(service, proposer=scripted, max_steps=6, max_calls=3, max_cost=5,
        timeout=1.0, clock=time.monotonic, price=lambda proposal: 1):
    start = clock()
    state = {"service": service, "status": "ready", "observations": [],
             "calls": 0, "steps": 0, "cost": 0, "trace": [], "outcome": None}
    signatures = {}
    def stop(reason, success=False):
        state["status"] = "completed" if success else "failed"
        state["outcome"] = reason
        return state
    for step in range(max_steps):
        if clock() - start >= timeout:
            return stop("time_budget")
        state["steps"] += 1
        state["remaining_seconds"] = max(0.0, timeout - (clock() - start))
        proposal = proposer(state)
        state["trace"].append({"proposal": proposal})
        if clock() - start >= timeout:
            return stop("time_budget")
        if not isinstance(proposal, dict):
            return stop("invalid_proposal")
        if proposal.get("action") == "finish":
            if any(o["status"] == "ok" for o in state["observations"]):
                return stop("success", True)
            return stop("unsupported_completion")
        if set(proposal) != {"action", "service"} or proposal["action"] != "lookup":
            return stop("invalid_proposal")
        if proposal["service"] != service:  # bind the action to the actual requested task
            return stop("changed_scope")
        if state["calls"] >= max_calls:
            return stop("call_budget")
        reserve = price(proposal)
        if reserve < 0 or state["cost"] + reserve > max_cost:
            return stop("cost_budget")
        signature = json.dumps(proposal, sort_keys=True)
        if signatures.get(signature, 0) >= 3:
            return stop("no_progress")
        signatures[signature] = signatures.get(signature, 0) + 1
        state["status"] = "waiting"
        state["calls"] += 1
        state["cost"] += reserve
        result = {"call_id": state["calls"], **lookup(service)}
        state["observations"].append(result)
        state["trace"].append({"observation": result})
        if result["status"] == "timeout":
            return stop("timeout")
        state["status"] = "observed"
    return stop("step_budget")


def lesson1(proposer=scripted, real=False):
    tasks = ["mail", "storage", "dns", "timeout", "missing"] * 4
    passed = 0
    for number, service in enumerate(tasks, 1):
        state = run(service, proposer)
        expected_success = service in SERVICES
        has_evidence = any(o["status"] == "ok" for o in state["observations"])
        # Runtime invariant is mandatory even if a real model chooses badly.
        assert state["status"] != "completed" or has_evidence
        correct = (state["outcome"] == "success") == expected_success
        passed += correct
        print(f"task {number:02} {service}: outcome={state['outcome']} decisions={state['steps']} calls={state['calls']} correct={correct}")
    if not real:
        assert passed == 20
    print(f"{'REAL MODEL' if real else 'SCRIPTED FIXTURE'} outcomes: {passed}/20; no unsupported completion allowed")


def lesson2():
    assert validate_local_url("http://localhost:1234/v1/chat/completions")
    for url in ("http://127.0.0.1:11434@example.org/", "http://localhost:1234@elsewhere.invalid/", "http://example.org:1234/", "http://user@localhost:1234/"):
        try:
            validate_local_url(url)
            raise AssertionError("nonlocal or userinfo endpoint accepted")
        except ValueError:
            pass
    try:
        NoRedirect().redirect_request(None, None, 302, "Found", {}, "http://elsewhere.invalid/")
        raise AssertionError("redirect accepted")
    except ValueError:
        pass
    failed = run("missing", max_steps=10, max_calls=9, max_cost=20)
    assert failed["outcome"] == "no_progress" and failed["calls"] == 3
    bounded = run("missing", max_calls=2)
    assert bounded["outcome"] == "call_budget" and bounded["calls"] == 2
    expensive = run("mail", max_cost=5, price=lambda p: 6)
    assert expensive["outcome"] == "cost_budget" and expensive["calls"] == 0
    reservations = iter([2, 4])
    partially_spent = run("missing", max_cost=5, price=lambda p: next(reservations))
    assert partially_spent["outcome"] == "cost_budget" and partially_spent["calls"] == 1 and partially_spent["cost"] == 2
    ticks = iter([0.0, 2.0])
    timed = run("mail", clock=lambda: next(ticks), timeout=1)
    assert timed["outcome"] == "time_budget" and timed["calls"] == 0
    unsupported = run("mail", proposer=lambda state: {"action": "finish"})
    assert unsupported["outcome"] == "unsupported_completion"
    success = run("mail")
    assert success["outcome"] == "success" and success["calls"] == 1
    print("PASS lesson 2: no-progress, call, prospective cost, deadline, unsupported finish, and success guards")


def cancel(subscription, actor, expected):
    if "cancel" not in actor["permissions"]:
        return {"status": "denied", "effects": 0}
    if expected != subscription["version"]:
        return {"status": "conflict", "effects": 0}
    if not subscription["eligible"] or not subscription["active"]:
        return {"status": "ineligible", "effects": 0}
    subscription["active"] = False
    subscription["version"] += 1
    return {"status": "canceled", "effects": 1}


def lesson3():
    for case in ("allowed", "read-only", "ineligible", "changed"):
        subscription = {"eligible": True, "active": True, "version": 1}
        observation = subscription.copy()
        actor = {"permissions": {"read", "cancel"} if case != "read-only" else {"read"}}
        if case == "ineligible":
            subscription["eligible"] = False
        if case == "changed":
            subscription["version"] += 1
            subscription["eligible"] = False
        result = cancel(subscription, actor, observation["version"])
        assert result["effects"] == (1 if case == "allowed" else 0)
        assert subscription["active"] == (case != "allowed")
        print(case, result)
    print("PASS lesson 3: only the authorized, current, eligible operation changes synthetic state")


def local_proposer(url, model):
    validate_local_url(url)
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
    def propose(state):
        instruction = ('Return ONLY a JSON object: {"action":"lookup","service":SERVICE} '
                       'or {"action":"finish"}. Finish only after an ok observation. '
                       'Do not change the requested service.')
        payload = {"model": model, "temperature": 0, "max_tokens": 80,
                   "messages": [{"role": "system", "content": instruction},
                                {"role": "user", "content": json.dumps(state)}]}
        request = urllib.request.Request(url, json.dumps(payload).encode(), {"Content-Type": "application/json"})
        try:
            with opener.open(request, timeout=max(0.01, min(5, state["remaining_seconds"]))) as response:
                content = json.load(response)["choices"][0]["message"]["content"]
            return json.loads(content)
        except (ValueError, KeyError, TimeoutError, OSError) as error:
            return {"action": "invalid", "error": type(error).__name__}
    return propose


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--lesson", choices=["1", "2", "3", "all"], default="all")
    parser.add_argument("--model-url")
    parser.add_argument("--model", default="")
    args = parser.parse_args()
    for number, function in enumerate((lesson1, lesson2, lesson3), 1):
        if args.lesson in (str(number), "all"):
            function()
    if args.model_url:
        if not args.model:
            parser.error("--model is required with --model-url")
        print("Optional actual local-model integration follows the deterministic checks.")
        lesson1(local_proposer(args.model_url, args.model), real=True)


if __name__ == "__main__":
    main()
