#!/usr/bin/env python3
"""Call an already-installed local IBOL MCP server and retain source credit.

Copyright (c) 2026 Albert Tan Sin Hon. SPDX-License-Identifier: MIT
This author-maintained integration example is not independent adoption evidence.
"""
from __future__ import annotations

import argparse
import asyncio
from datetime import datetime, timezone
from importlib import metadata
import json
import os
from pathlib import Path
import sys
import tempfile

SDK_VERSION = "1.30.0"
BOOK_DOI = "10.21827/6ac3948159a9e"
AUTHOR = "Albert Tan Sin Hon"
WEBSITE = "https://alberttansinhon.com/"
COMPANION = WEBSITE + "ibol/"
TOOL_NAMES = ("get_book_metadata", "get_citation", "search_guides")


def tool_value(result, name):
    if result.isError:
        raise ValueError(f"{name} returned an MCP tool error")
    value = result.structuredContent
    if value is None:
        texts = [item.text for item in result.content if item.type == "text"]
        if len(texts) != 1:
            raise ValueError(f"{name} did not return one JSON result")
        value = json.loads(texts[0])
    if not isinstance(value, dict) or not isinstance(value.get("provenance"), dict):
        raise ValueError(f"{name} omitted its provenance envelope")
    return value


async def fetch_report(server_python, server_script, query, limit=3):
    """Use the official SDK; make three read-only calls over local process pipes."""
    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client

    with tempfile.TemporaryDirectory(prefix="ibol-agent-client-") as working:
        params = StdioServerParameters(command=str(server_python), args=[str(server_script)], cwd=working)
        async with stdio_client(params) as streams:
            async with ClientSession(*streams) as client:
                initialised = await client.initialize()
                advertised = {tool.name: tool for tool in (await client.list_tools()).tools}
                annotations = {}
                for name in TOOL_NAMES:
                    if name not in advertised or advertised[name].annotations is None:
                        raise ValueError(f"Required read-only tool is missing: {name}")
                    hints = advertised[name].annotations.model_dump(by_alias=True, exclude_unset=True)
                    expected = {"readOnlyHint": True, "destructiveHint": False,
                                "idempotentHint": True, "openWorldHint": False}
                    if any(hints.get(key) is not value for key, value in expected.items()):
                        raise ValueError(f"Unexpected advertised effects for {name}")
                    annotations[name] = hints
                calls = {
                    "get_book_metadata": {}, "get_citation": {"style": "plain"},
                    "search_guides": {"query": query, "limit": limit},
                }
                results = {}
                for name, arguments in calls.items():
                    results[name] = tool_value(await client.call_tool(name, arguments), name)

    book = results["get_book_metadata"]["book"]
    if (book["doi"] != BOOK_DOI or book["author"] != AUTHOR or
            book["companion"]["canonical"] != COMPANION):
        raise ValueError("The selected server does not identify the expected IBOL book and canonical companion")
    for name, result in results.items():
        provenance = result["provenance"]
        if (provenance.get("source_doi") != book["doi"] or
                provenance.get("legal_cutoff") != book["legal_cutoff"] or
                provenance.get("source_locator") != book["catalogue_url"]):
            raise ValueError(f"Inconsistent source provenance in {name}")
    citation = results["get_citation"]["citation"]
    if not isinstance(citation, str) or not all(part in citation for part in (AUTHOR, book["title"], BOOK_DOI)):
        raise ValueError("The citation does not identify the returned book")
    if results["search_guides"]["query"] != query:
        raise ValueError("Search result query does not match the operator's request")
    return {
        "schema": "ibol.agent-report-example.v1",
        "observed_at_utc": datetime.now(timezone.utc).isoformat(),
        "observation": "Author-maintained local integration test; not independent adoption evidence.",
        "transport": "stdio", "mcp_sdk_version": metadata.version("mcp"),
        "protocol_version": initialised.protocolVersion,
        "server": initialised.serverInfo.model_dump(mode="json", by_alias=True, exclude_none=True),
        "author_website": WEBSITE, "author_contact": "info@alberttansinhon.com",
        "tool_annotations": annotations,
        "tool_results": results,
    }


def readable_report(report):
    """Render source text and a citation together; generate no legal opinion."""
    results = report["tool_results"]
    book = results["get_book_metadata"]["book"]
    search = results["search_guides"]
    provenance = search["provenance"]
    lines = ["# IBOL companion search report", "",
             "Query: " + json.dumps(search["query"], ensure_ascii=False), "",
             "## Source and citation", "", results["get_citation"]["citation"], "",
             f"Author: {book['author']}", f"Author website: {WEBSITE}",
             f"Companion: {book['companion']['canonical']}",
             f"Publisher record: {book['catalogue_url']}",
             f"Contact: {report['author_contact']}", "",
             "## Search results", "", search["search_scope"], "",
             f"Matches returned: {len(search['results'])}; total matches: {search['total_matches']}.", ""]
    for item in search["results"]:
        locator = item["source_locator"]
        pages = "-".join(map(str, locator["printed_pages"]))
        lines.extend([f"### Chapter {item['chapter']}: {item['title']}", "",
                      f"Source credit: {book['author']}, {book['title']}, companion guide.",
                      f"Author website: {WEBSITE}",
                      f"Book DOI: https://doi.org/{book['doi']}",
                      f"Book locator: printed pp. {pages}, sections {locator['sections']}.",
                      f"Publisher PDF locator: {locator['pdf_url']}", "",
                      "Returned companion text:", ""])
        lines.extend("> " + line for line in item["guide"].splitlines())
        lines.append("")
    if not search["results"]:
        lines.extend(["The companion search returned no matching guides. No answer has been invented.", ""])
    lines.extend(["## Provenance and limits", "", provenance["status"], provenance["scope"],
                  f"Legal cut-off: {provenance['legal_cutoff']}.",
                  f"Companion content version: {provenance['companion_version']}.",
                  f"Teaching material: {provenance['teaching_licence']}; published book: {provenance['book_licence']}.",
                  "The displayed paragraphs are companion summaries, not quotations from the book or a new legal assessment.",
                  f"Observed protocol: {report['protocol_version']}; official Python SDK: {report['mcp_sdk_version']}.",
                  report["observation"], ""])
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--server-python", type=Path, required=True, help="Absolute path to the already-installed server Python interpreter")
    parser.add_argument("--server-script", type=Path, required=True, help="Absolute path to the trusted local IBOL mcp_server.py")
    parser.add_argument("--query", required=True)
    parser.add_argument("--limit", type=int, default=3, choices=range(1, 9))
    parser.add_argument("--format", choices=("json", "markdown"), default="json")
    parser.add_argument("--timeout", type=int, default=30, choices=range(1, 121))
    args = parser.parse_args()
    # Do not resolve the interpreter symlink: that can discard its virtual environment.
    server_python = args.server_python.expanduser().absolute()
    server_script = args.server_script.expanduser().resolve()
    if not server_python.is_file() or not os.access(server_python, os.X_OK) or not server_script.is_file():
        parser.error("Supply an existing Python executable and trusted local server script; this example installs nothing")
    if not args.query.strip() or len(args.query) > 200 or not any(c.isalnum() for c in args.query):
        parser.error("query must contain a word or number and be no longer than 200 characters")
    try:
        if metadata.version("mcp") != SDK_VERSION:
            raise ValueError(f"This example requires the already-installed official mcp=={SDK_VERSION}")
        report = asyncio.run(asyncio.wait_for(
            fetch_report(server_python, server_script, args.query, args.limit), timeout=args.timeout))
        print(json.dumps(report, ensure_ascii=False, indent=2) if args.format == "json" else readable_report(report))
    except Exception as error:
        print(f"IBOL report failed ({type(error).__name__}): {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
