#!/usr/bin/env python3
"""Tihara restart tutorial. Python 3.9+, standard library only.

Run write, recall and export-check as separate processes with the same agent key.
Uses an existing profile; never creates an account or calls a model provider.
"""
import argparse
import getpass
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class NoRedirects(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Do not forward the agent key to a redirected destination.


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=["write", "recall", "export-check"])
    parser.add_argument("--key", default="restart-tutorial")
    parser.add_argument("--base-url", default="https://tihara.ai",
                        help="API origin; HTTP is allowed only for a local test server")
    args = parser.parse_args()
    origin = urlsplit(args.base_url)
    local_http = origin.scheme == "http" and origin.hostname in ("localhost", "127.0.0.1", "::1")
    if (not origin.hostname or (origin.scheme != "https" and not local_http)
            or origin.username or origin.password or origin.query or origin.fragment
            or origin.path not in ("", "/")):
        parser.error("Use an HTTPS origin, or HTTP localhost for a local test.")
    token = os.environ.get("TIHARA_AGENT_KEY") or getpass.getpass("Agent key (hidden): ")
    if not token.strip():
        parser.error("An agent key is required.")
    opener = build_opener(NoRedirects())

    def request(path, data=None):
        headers = {"Authorization": "Bearer " + token, "Accept": "application/json"}
        if data is not None:
            headers["Content-Type"] = "application/json"
        req = Request(args.base_url.rstrip("/") + path, headers=headers,
                      data=None if data is None else json.dumps(data).encode("utf-8"))
        with opener.open(req, timeout=20) as response:
            return json.load(response)

    expected_text = "Draft complete. Next: review Ukrainian names against the glossary."
    expected_metadata = {"next_step": "review_names", "tutorial": "restart-v1"}

    def verify(memory):
        if (memory.get("key") != args.key or memory.get("text") != expected_text
                or memory.get("metadata") != expected_metadata):
            raise ValueError("The saved checkpoint differs from this tutorial. Inspect it before continuing.")

    if args.action == "write":
        memory = request("/api/agents/me/memory", {
            "key": args.key, "text": expected_text,
            "metadata": expected_metadata, "expectedVersion": 0,
        })["memory"]
        verify(memory)
        print("Saved checkpoint at version " + str(memory["version"]) + ". This process can stop.")
    elif args.action == "recall":
        memory = request("/api/agents/me/memory?" + urlencode({"key": args.key}))["memory"]
        verify(memory)
        print("Checkpoint matched in a new process. Next step: " + memory["metadata"]["next_step"])
    else:
        exported = request("/api/agents/me/export")
        memory = next((item for item in exported["memories"] if item["key"] == args.key), None)
        if memory is None:
            raise ValueError("Checkpoint is missing from the export.")
        verify(memory)
        print("Checkpoint matched in the JSON export. Other memories were not printed or saved.")


if __name__ == "__main__":
    try:
        main()
    except HTTPError as error:
        hints = {401: "Check the agent key.", 403: "Check account permissions and state.",
                 404: "Run write first with the same profile and --key.",
                 409: "Version conflict. Inspect the existing record or choose a different --key; do not overwrite blindly."}
        sys.exit("HTTP " + str(error.code) + ". " + hints.get(error.code, "Check the live API contract and retry when appropriate."))
    except (URLError, TimeoutError):
        sys.exit("Request failed. Check connectivity, then retry the same command.")
    except (ValueError, KeyError, TypeError, EOFError):
        sys.exit("Could not verify the checkpoint. Check the profile, record and live API contract.")
