#!/usr/bin/env python3
"""Bounded, headless Ewooks MCP 0.2 snapshot reader. Python 3.10+, standard library."""

import argparse
import datetime as dt
import json
import os
from pathlib import Path
import re
import tempfile
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener

ENDPOINTS = {
    "https://mcp.ewooks.fi/mcp",
}
MAX_RESPONSE_BYTES = 16 * 1024 * 1024
PROTOCOL = "2025-11-25"


class McpError(Exception):
    """Safe operational error; never includes a credential or raw fleet response."""


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise McpError("Redirect refused. Verify the configured fixed HTTPS endpoint.")


class EwooksClient:
    def __init__(self, endpoint, key, opener=None):
        if endpoint not in ENDPOINTS:
            raise McpError("Use an exact supported HTTPS production or demo MCP endpoint.")
        if not re.fullmatch(r"ewmcp_[a-f0-9]{64}", key):
            raise McpError("Set a valid API key through EWOOKS_MCP_KEY.")
        self.endpoint = endpoint
        self.key = key
        self.opener = opener or build_opener(NoRedirect())
        self.sequence = 0
        self.protocol = PROTOCOL

    def request(self, method, params, notification=False):
        self.sequence += 1
        message = {"jsonrpc": "2.0", "method": method, "params": params}
        if not notification:
            message["id"] = self.sequence
        req = Request(self.endpoint, data=json.dumps(message).encode("utf-8"), method="POST", headers={
            "Authorization": "Bearer " + self.key,
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
            "MCP-Protocol-Version": self.protocol,
        })
        try:
            with self.opener.open(req, timeout=30) as response:
                if notification:
                    if response.status not in (200, 202, 204):
                        raise McpError("Initialization notification was not acknowledged.")
                    return None
                raw = response.read(MAX_RESPONSE_BYTES + 1)
                if len(raw) > MAX_RESPONSE_BYTES:
                    raise McpError("Response exceeds the client size limit.")
        except HTTPError as exc:
            raise McpError(f"MCP HTTP {exc.code}. Check access or retry later with bounded backoff.") from None
        except (URLError, TimeoutError, OSError):
            raise McpError("MCP connection failed. Keep previous transfer state and investigate.") from None
        try:
            body = json.loads(raw)
        except (ValueError, UnicodeError):
            raise McpError("MCP returned invalid JSON.") from None
        if not isinstance(body, dict) or body.get("jsonrpc") != "2.0" or body.get("id") != self.sequence:
            raise McpError("Unexpected JSON-RPC response.")
        if "error" in body:
            raise McpError("JSON-RPC request failed. Check protocol and method.")
        result = body.get("result")
        if not isinstance(result, dict) or result.get("isError"):
            raise McpError("MCP tool failed. Check the documented limits, cursor and authorization.")
        return result

    def initialize(self):
        result = self.request("initialize", {
            "protocolVersion": PROTOCOL, "capabilities": {},
            "clientInfo": {"name": "ewooks-python-snapshot-example", "version": "1.0"},
        })
        # This example is reviewed for the 0.2 contract. Require review before a new minor/major.
        version = result.get("serverInfo", {}).get("version", "")
        if not re.fullmatch(r"0\.2\.[0-9]+", version):
            raise McpError("This example requires a verified Ewooks MCP 0.2 deployment.")
        if result.get("protocolVersion") != PROTOCOL:
            raise McpError("Unexpected negotiated protocol version.")
        self.request("notifications/initialized", {}, notification=True)

    def records(self, resource, first_date, last_date, driver=None):
        if resource not in ("drives", "work-sessions"):
            raise McpError("Unsupported resource.")
        first, last = dt.date.fromisoformat(first_date), dt.date.fromisoformat(last_date)
        if last < first or (last - first).days >= 366:
            raise McpError("Choose a date range of at most 366 inclusive days.")
        field = "drives" if resource == "drives" else "work_sessions"
        args = {"from": first_date, "to": last_date, "pagination": "snapshot", "limit": 100}
        if driver is not None:
            args["driver"] = driver
        cursors, identities = set(), set()
        expected_fleet = None
        for _ in range(10000):
            result = self.request("tools/call", {"name": "list_" + field, "arguments": args})
            data = result.get("structuredContent")
            if not isinstance(data, dict) or data.get("pagination") != "snapshot" or "next_cursor" not in data:
                raise McpError("Snapshot pagination is unavailable; no live-pagination fallback is allowed.")
            rows = data.get(field)
            if not isinstance(rows, list) or len(rows) > 100:
                raise McpError("Unexpected page shape.")
            for row in rows:
                if not isinstance(row, dict) or row.get("id") is None or not isinstance(row.get("fleet_id"), str) or not row["fleet_id"]:
                    raise McpError("A source record is missing its identity.")
                expected_fleet = expected_fleet or row["fleet_id"]
                if row["fleet_id"] != expected_fleet:
                    raise McpError("Unexpected fleet change. Stop and investigate.")
                identity = (row["fleet_id"], str(row["id"]))
                if identity in identities:
                    raise McpError("Duplicate source identity in one snapshot. Stop and reconcile.")
                identities.add(identity)
                yield row
            cursor = data["next_cursor"]
            if cursor is None:
                return
            if not isinstance(cursor, str) or not cursor or cursor in cursors:
                raise McpError("Invalid or repeated continuation cursor.")
            cursors.add(cursor)
            args["cursor"] = cursor
        raise McpError("Page limit reached. Stop and investigate.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--from", dest="first_date", required=True)
    parser.add_argument("--to", dest="last_date", required=True)
    parser.add_argument("--resource", choices=["drives", "work-sessions"], default="drives")
    parser.add_argument("--driver")
    parser.add_argument("--output", type=Path, help="Create a new sensitive NDJSON file only after a complete successful read")
    args = parser.parse_args()
    temporary = None
    output = None
    try:
        client = EwooksClient(os.getenv("EWOOKS_MCP_URL", "https://mcp.ewooks.fi/mcp"), os.getenv("EWOOKS_MCP_KEY", ""))
        if args.output:
            if args.output.exists():
                raise McpError("Output already exists; choose a new file.")
            output = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=args.output.parent, prefix=".ewooks-", delete=False)
            temporary = Path(output.name)
        client.initialize()
        count = 0
        for row in client.records(args.resource, args.first_date, args.last_date, args.driver):
            count += 1
            if output:
                output.write(json.dumps(row, ensure_ascii=False) + "\n")
        if output:
            output.close()
            # Hard-link publication is atomic and refuses to overwrite an existing destination.
            os.link(temporary, args.output)
        print(f"Read {count} records from one bounded snapshot. No downstream writes performed.")
    except (McpError, ValueError, OSError) as exc:
        # Do not echo arbitrary OS errors: they may include private file paths.
        parser.exit(1, str(exc) + "\n" if isinstance(exc, McpError) else "Read failed; no complete output was published.\n")
    finally:
        if output and not output.closed:
            output.close()
        if temporary:
            temporary.unlink(missing_ok=True)


if __name__ == "__main__":
    main()
