#!/usr/bin/env python3
"""Initrix agent connection checker. Linux, Python 3, and secret-tool only.

connect validates a hidden MCP key before saving it in the OS keyring.
status reads that slot and calls initrix_whoami. --watch stays in the foreground.
This is an agent/API connection check; computer status belongs in Compute.
"""

import argparse
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
import getpass
import http.client
import json
import re
import shutil
import signal
import subprocess
import sys
import time
import uuid
import warnings

VERSION = "1.0.0"
MCP_HOST = "api.initrix.dev"
MCP_PATH = "/mcp"
PROTOCOL = "2026-07-28"
KEYRING_ATTRIBUTES = ("service", "initrix.dev", "purpose", "codex-verification")
KEY_PATTERN = re.compile(r"itx_mcp_[A-Za-z0-9_-]{32,128}\Z")
PERMISSION_PATTERN = re.compile(r"[a-z]+:[a-z]+\Z")
ABILITIES = {"lab:read": "read Lab work and progress", "compute:read": "check computers and shared folders",
             "compute:manage": "rent and manage cloud computers (charges apply)",
             "storage:manage": "manage encrypted storage on connected computers"}
NETWORK_TIMEOUT = 10
KEYRING_TIMEOUT = 8
MAX_REPLY = 65536
_run = subprocess.run  # Tests replace this indirection, never subprocess globally.
_sleep = time.sleep


@dataclass(frozen=True)
class Status:
    name: str
    detail: str
    lines: tuple = ()
    diagnostics: tuple = ()

    @property
    def exit_code(self):
        return 0 if self.name == "Connected" else 1


class KeyringProblem(Exception):
    pass


def timestamp():
    return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")


def say(text):
    print(f"[{timestamp()}] {text}", flush=True)


def safe_text(value, key):
    text = str(value).replace(key, "[redacted]")
    return "".join(character if character.isprintable() else " " for character in text)[:120]


def secret_tool(arguments, secret=None):
    executable = shutil.which("secret-tool")
    if not executable:
        raise KeyringProblem("secret-tool is missing. Install your Linux distribution's libsecret-tools package.")
    try:
        return _run([executable, *arguments], input=secret, text=True,
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                    timeout=KEYRING_TIMEOUT, check=False)
    except (OSError, subprocess.TimeoutExpired):
        raise KeyringProblem("The Linux keyring did not answer. Unlock it and retry.") from None


def saved_key():
    result = secret_tool(["lookup", *KEYRING_ATTRIBUTES])
    if result.returncode == 1 and not result.stderr:
        return None
    if result.returncode != 0:
        raise KeyringProblem("The Linux keyring is unavailable or locked. Unlock it and retry.")
    value = result.stdout.rstrip("\r\n")
    return value or None


def save_key(key):
    result = secret_tool(["store", "--label=Initrix MCP agent connection", *KEYRING_ATTRIBUTES], key + "\n")
    if result.returncode != 0 or saved_key() != key:
        raise KeyringProblem("Could not confirm the keyring save. Run status before retrying.")


@contextmanager
def network_deadline():
    def expired(_signum, _frame):
        raise TimeoutError("MCP check timed out")
    previous = signal.signal(signal.SIGALRM, expired)
    previous_timer = signal.setitimer(signal.ITIMER_REAL, NETWORK_TIMEOUT)
    try:
        yield
    finally:
        signal.setitimer(signal.ITIMER_REAL, *previous_timer)
        signal.signal(signal.SIGALRM, previous)


def read_reply(response):
    data = bytearray()
    events = response.getheader("Content-Type", "").split(";", 1)[0].strip() == "text/event-stream"
    while True:
        chunk = response.read1(4096)
        if not chunk:
            break
        data.extend(chunk)
        if len(data) > MAX_REPLY:
            raise ValueError("Reply too large")
        if events:
            for event in bytes(data).replace(b"\r\n", b"\n").split(b"\n\n")[:-1]:
                payload = b"\n".join(line[5:].lstrip() for line in event.split(b"\n") if line.startswith(b"data:"))
                if not payload:
                    continue
                message = json.loads(payload)
                if isinstance(message, dict) and message.get("id") == 1 and ("result" in message or "error" in message):
                    return message
    if events:
        raise ValueError("No complete MCP event")
    return json.loads(data)


def post_identity(key, connection_factory=http.client.HTTPSConnection):
    client = {"name": "initrix-terminal-status", "version": VERSION}
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
        "name": "initrix_whoami", "arguments": {}, "_meta": {
            "io.modelcontextprotocol/protocolVersion": PROTOCOL,
            "io.modelcontextprotocol/clientCapabilities": {},
            "io.modelcontextprotocol/clientInfo": client}}})
    connection = connection_factory(MCP_HOST, timeout=NETWORK_TIMEOUT)
    try:
        with network_deadline():
            connection.request("POST", MCP_PATH, body, headers={
                "Authorization": "Bearer " + key, "Content-Type": "application/json",
                "Accept": "application/json, text/event-stream", "MCP-Protocol-Version": PROTOCOL,
                "MCP-Method": "tools/call", "MCP-Name": "initrix_whoami",
                "User-Agent": "initrix-terminal-status/" + VERSION})
            response = connection.getresponse()
            # http.client never follows redirects; credentials stay at this origin.
            if 300 <= response.status < 400:
                return response.status, {}
            try:
                reply = read_reply(response)
            except ValueError:
                if response.status == 200:
                    raise
                reply = {}
            return response.status, reply
    finally:
        connection.close()


def refusal(code, http_status=200):
    if code in {"agent_expired", "expired_token", "key_expired", "token_expired"}:
        return Status("Expired", "Create a new MCP key in Settings → Agents, then run connect.")
    if code == "agent_revoked":
        return Status("Expired or revoked", "This connection was revoked. Create a new MCP key, then run connect.")
    if http_status == 401:
        return Status("Expired or not accepted", "The service did not accept this key. It may be expired, revoked or incorrect. Create a new key in Settings → Agents, then run connect.")
    if http_status == 403 or code == "agent_forbidden":
        return Status("Missing permission", "The service refused this agent connection. Review its permissions in Settings → Agents.")
    return Status("Service unavailable", "MCP identity could not be verified. Retry later.")


def check_key(key, transport=post_identity):
    if not KEY_PATTERN.fullmatch(key):
        return Status("Expired or not accepted", "This is not an Initrix MCP connection key. Use a key from Settings → Agents.")
    try:
        http_status, reply = transport(key)
        if 300 <= http_status < 400:
            return Status("Service unavailable", "MCP redirected the request. The redirect was refused; the key was not forwarded.")
        if http_status != 200:
            code = reply.get("error") if isinstance(reply, dict) else None
            return refusal(code if isinstance(code, str) else None, http_status)
        if not isinstance(reply, dict):
            raise ValueError("Unexpected reply")
        if reply.get("jsonrpc") != "2.0" or reply.get("id") != 1:
            raise ValueError("Unexpected MCP message")
        if "error" in reply:
            error = reply["error"]
            return refusal(error.get("data", {}).get("error") if isinstance(error, dict) and isinstance(error.get("data"), dict) else None)
        result = reply["result"]
        content = result["structuredContent"]
        if result.get("isError"):
            return refusal(content.get("error"))
        if result.get("resultType") != "complete" or not isinstance(content, dict):
            raise ValueError("Incomplete MCP result")
        user = str(uuid.UUID(content["user_id"]))
        organization = str(uuid.UUID(content["organization_id"]))
        permissions = content["permissions"]
        if not isinstance(permissions, list) or len(permissions) > 16 or any(not isinstance(value, str) or not PERMISSION_PATTERN.fullmatch(value) or len(value) > 32 for value in permissions):
            raise ValueError("Invalid permissions")
        info = content["connection"]
        if not isinstance(info, dict) or info.get("kind") != "key":
            raise ValueError("Not a connection key")
        uuid.UUID(info["id"])
        lines = ["Connection: " + (safe_text(info["label"], key) if isinstance(info.get("label"), str) else "Saved Initrix key")]
        allowed = [description for permission, description in ABILITIES.items() if permission in permissions]
        if any(permission not in ABILITIES for permission in permissions):
            allowed.append("additional access (see --details)")
        lines.extend(["Key allows:", *("  - " + value for value in allowed)] if allowed else ["Key allows: no access"])
        diagnostics = ["Service: https://api.initrix.dev/mcp", "User ID: " + user, "Organization ID: " + organization,
                       "Permission codes: " + (", ".join(sorted(set(permissions))) or "None")]
        if isinstance(content.get("role"), str):
            diagnostics.append("Role: " + safe_text(content["role"], key))
        expiry = info.get("expires_at")
        if expiry is not None:
            when = datetime.fromisoformat(expiry.replace("Z", "+00:00"))
            if when.tzinfo is None:
                raise ValueError("Invalid expiry")
            if when <= datetime.now(timezone.utc):
                return Status("Expired", "The reported key expiry has passed by this computer's clock. Check its clock or create a new MCP key.")
            diagnostics.append("Key expires: " + when.astimezone(timezone.utc).isoformat(timespec="seconds"))
        if not permissions:
            return Status("Missing permission", "Your key was recognized, but it has no access. Review Settings → Agents.", tuple(lines), tuple(diagnostics))
        return Status("Connected", "MCP service reachable; agent key accepted.", tuple(lines), tuple(diagnostics))
    except (OSError, http.client.HTTPException, TimeoutError, ValueError, TypeError, KeyError, AttributeError):
        return Status("Service unavailable", "Could not check Initrix right now. Check your connection and try again.")


def status(transport=post_identity):
    try:
        key = saved_key()
    except KeyringProblem as problem:
        return Status("Keyring unavailable", str(problem))
    if key is None:
        return Status("Missing", "No MCP key is saved in the Linux keyring. Run connect.")
    return check_key(key, transport)


def show(result, metadata=True, diagnostic=False):
    say("Agent connection: " + result.name + (" — checked just now." if result.name == "Connected" else " — " + result.detail))
    if metadata:
        for line in result.lines:
            print("  " + line, flush=True)
        if diagnostic:
            for line in result.diagnostics:
                print("  " + line, flush=True)


class Parser(argparse.ArgumentParser):
    def error(self, _message):
        # argparse's default errors echo unknown argv, which may contain a pasted key.
        self.exit(2, "Invalid command or option. Use --help; enter your key only at the hidden connect prompt.\n")


def main(argv=None, transport=post_identity):
    parser = Parser(description="Check your Initrix agent connection. Computer/worker status is in Compute.")
    parser.add_argument("--version", action="version", version=VERSION)
    commands = parser.add_subparsers(dest="command", required=True)
    connect = commands.add_parser("connect", help="Validate a hidden connection key, then save it in the Linux keyring")
    connect.add_argument("--details", action="store_true", help="Also show diagnostic IDs and permission codes")
    checks = commands.add_parser("status", help="Check the saved agent connection and its access")
    checks.add_argument("--details", action="store_true", help="Also show diagnostic IDs and permission codes")
    checks.add_argument("--watch", action="store_true", help="Repeat in this foreground terminal until Ctrl+C")
    checks.add_argument("--interval", type=int, help="Watch interval in seconds, 10–300 (default 30)")
    args = parser.parse_args(argv)
    if args.command == "status":
        if args.interval is not None and not args.watch:
            parser.exit(2, "--interval requires status --watch.\n")
        args.interval = 30 if args.interval is None else args.interval
        if not 10 <= args.interval <= 300:
            parser.exit(2, "The watch interval must be between 10 and 300 seconds.\n")
    if args.command == "connect":
        if not sys.stdin.isatty():
            show(Status("Missing", "Run connect in an interactive terminal so key entry can stay hidden."))
            return 1
        say("[1/3] Enter the Initrix connection key from Settings → Agents.")
        try:
            with warnings.catch_warnings():
                warnings.simplefilter("error", getpass.GetPassWarning)
                key = getpass.getpass("Initrix connection key (hidden): ").strip()
        except (EOFError, getpass.GetPassWarning):
            show(Status("Missing", "A hidden terminal prompt is unavailable. Nothing was saved."))
            return 1
        say("[2/3] Validating agent identity and access with Initrix…")
        result = check_key(key, transport)
        if result.name != "Connected":
            show(result, diagnostic=args.details)
            say("Validation failed. The existing keyring entry was not changed.")
            return result.exit_code
        say("[3/3] Saving the verified key in the Linux keyring…")
        try:
            save_key(key)
        except KeyringProblem as problem:
            show(Status("Keyring unavailable", str(problem)))
            return 1
        show(result, diagnostic=args.details)
        say("Saved. Use this helper's status command, or status --watch for a foreground agent-connection heartbeat.")
        return 0
    if args.watch:
        say(f"Watching your agent connection; {args.interval}s between checks. Ctrl+C stops it. See Compute for computer/worker status.")
    previous = None
    count = 0
    while True:
        count += 1
        if count == 1 or not args.watch:
            say("Checking your agent connection…")
        result = status(transport)
        show(result, result != previous, args.details)
        if not args.watch:
            return result.exit_code
        previous = result
        _sleep(args.interval)


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        say("Agent connection watch/input stopped.")
        sys.exit(130)
    except BrokenPipeError:
        sys.exit(0)
