#!/usr/bin/env python3
"""Local MCP tools for AKI.Gate. Uses the API key from AKIGATE_API_KEY."""
import argparse
import base64
import binascii
import json
import os
import shutil
import subprocess
import sys
import urllib.error
import urllib.request
import uuid
import zipfile
from pathlib import Path
from xml.etree import ElementTree

API = "https://akigate.ru"
MAX_REFERENCE = 6 * 1024 * 1024
MAX_DOCUMENT = 20 * 1024 * 1024
MAX_TEXT = 160_000
TOOLS = [
    {
        "name": "generate_image",
        "description": "Generate an image with AKI.Gate GPT Image 2. To edit a local reference or a previous result, provide its workspace path. Returns the image and a local file link.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "prompt": {"type": "string", "minLength": 1, "maxLength": 8000},
                "reference_path": {"type": "string", "description": "Optional PNG/JPEG path in the current project"},
                "size": {"enum": ["1024x1024", "1536x1024", "1024x1536"]},
                "quality": {"enum": ["low", "medium", "high"]},
            },
            "required": ["prompt"],
            "additionalProperties": False,
        },
    },
    {
        "name": "read_document",
        "description": "Extract text locally from an attached or workspace file. Supports UTF-8 text and code, DOCX, and PDFs with a text layer when pdftotext is installed.",
        "inputSchema": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"],
            "additionalProperties": False,
        },
    },
]
TEXT_SUFFIXES = set(".txt .md .csv .tsv .json .jsonl .xml .yaml .yml .log .ini .toml .sql .py .js .ts .jsx .tsx .go .rs .kt .java .cs .rb .html .css .sh .rtf".split())


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args):
        return None


def workspace_file(root, name, limit):
    path = (root / name).resolve(strict=True)
    if not path.is_relative_to(root) or not path.is_file():
        raise ValueError("Select a file inside the current project.")
    if path.stat().st_size > limit:
        raise ValueError("The file exceeds the size limit.")
    return path


def generate(root, arguments):
    token = os.environ.get("AKIGATE_API_KEY", "").strip()
    if not token:
        key_file = Path.home() / ".config" / "akigate" / "api-key"
        if key_file.is_file() and (os.name == "nt" or key_file.stat().st_mode & 0o077 == 0):
            token = key_file.read_text(encoding="utf-8").strip()
    if not token:
        raise ValueError("Set AKIGATE_API_KEY or put a key with access to gpt-image-2 in ~/.config/akigate/api-key (mode 600).")
    prompt = arguments.get("prompt", "").strip()
    if not prompt or len(prompt) > 8000:
        raise ValueError("Provide a prompt of 1 to 8000 characters.")
    payload = {
        "model": "gpt-image-2", "prompt": prompt, "n": 1,
        "size": arguments.get("size", "1024x1024"),
        "quality": arguments.get("quality", "medium"), "output_format": "png",
    }
    if arguments.get("reference_path"):
        path = workspace_file(root, arguments["reference_path"], MAX_REFERENCE)
        source = path.read_bytes()
        if source.startswith(b"\x89PNG\r\n\x1a\n"):
            media = "image/png"
        elif source.startswith(b"\xff\xd8\xff"):
            media = "image/jpeg"
        else:
            raise ValueError("Use a PNG or JPEG reference.")
        data = base64.b64encode(source).decode("ascii")
        payload["input_references"] = [{"type": "image_url", "image_url": {"url": f"data:{media};base64,{data}"}}]
    request = urllib.request.Request(
        API + "/v1/images/generations", json.dumps(payload).encode("utf-8"),
        {"Authorization": "Bearer " + token, "Content-Type": "application/json"}, method="POST",
    )
    try:
        with urllib.request.build_opener(NoRedirect()).open(request, timeout=180) as response:
            result = json.loads(response.read(24 * 1024 * 1024))
    except urllib.error.HTTPError as error:
        code = "request_error"
        try:
            code = json.loads(error.read(65536)).get("error", {}).get("code", code)
        except (ValueError, AttributeError):
            pass
        raise ValueError(f"AKI.Gate returned HTTP {error.code} ({code}).") from None
    try:
        encoded = result["data"][0]["b64_json"]
        image = base64.b64decode(encoded, validate=True)
    except (KeyError, IndexError, TypeError, binascii.Error):
        raise ValueError("AKI.Gate returned no readable image.") from None
    if not image.startswith(b"\x89PNG\r\n\x1a\n"):
        raise ValueError("AKI.Gate returned an unexpected image format.")
    directory = root / "aki-images"
    directory.mkdir(exist_ok=True)
    if directory.is_symlink() or not directory.is_dir():
        raise ValueError("The project output directory must be a real directory.")
    output = directory / (str(uuid.uuid4()) + ".png")
    with output.open("xb") as stream:
        stream.write(image)
    return [
        {"type": "text", "text": f"Image saved at {output.relative_to(root).as_posix()}. Use this path as reference_path for follow-up edits."},
        {"type": "image", "data": encoded, "mimeType": "image/png", "annotations": {"audience": ["user"]}},
    ]


def read_document(root, arguments):
    source = workspace_file(root, arguments["path"], MAX_DOCUMENT)
    suffix = source.suffix.lower()
    if suffix in TEXT_SUFFIXES:
        with source.open(encoding="utf-8-sig") as stream:
            text = stream.read(MAX_TEXT + 1)
    elif suffix == ".docx":
        with zipfile.ZipFile(source) as archive:
            member = archive.getinfo("word/document.xml")
            if member.file_size > MAX_DOCUMENT:
                raise ValueError("DOCX text exceeds the size limit.")
            with archive.open(member) as stream:
                document = ElementTree.fromstring(stream.read(MAX_DOCUMENT + 1))
        ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
        text = "\n".join("".join(t.text or "" for t in p.findall(".//w:t", ns)) for p in document.findall(".//w:p", ns))
    elif suffix == ".pdf":
        executable = shutil.which("pdftotext")
        if executable is None:
            raise ValueError("Install pdftotext (Poppler) to read PDFs with a text layer.")
        process = subprocess.run(
            [executable, "-f", "1", "-l", "100", str(source), "-"],
            capture_output=True, timeout=25, check=False,
        )
        if process.returncode != 0:
            raise ValueError("The PDF could not be read. Check encryption or file integrity.")
        text = process.stdout[: MAX_TEXT * 4 + 1].decode("utf-8", errors="replace")
    else:
        raise ValueError("Use a UTF-8 text/code file, DOCX, or a PDF with a text layer.")
    if not text.strip():
        raise ValueError("The file contains no extractable text.")
    note = "\n[Text truncated.]" if len(text) > MAX_TEXT else ""
    return [{"type": "text", "text": f"File: {source.name}\n\n{text[:MAX_TEXT]}{note}"}]


def reply(message, root):
    request_id = message.get("id")
    if "id" not in message:
        return None
    method = message.get("method")
    params = message.get("params") or {}
    result = {"jsonrpc": "2.0", "id": request_id}
    if method == "initialize":
        requested = params.get("protocolVersion")
        supported = {"2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"}
        result["result"] = {
            "protocolVersion": requested if requested in supported else "2025-11-25",
            "capabilities": {"tools": {}},
            "serverInfo": {"name": "aki-gate-images", "version": "1.0.0"},
        }
    elif method == "ping":
        result["result"] = {}
    elif method == "tools/list":
        result["result"] = {"tools": TOOLS}
    elif method == "tools/call":
        try:
            name = params.get("name")
            arguments = params.get("arguments") or {}
            if name == "generate_image":
                content = generate(root, arguments)
            elif name == "read_document":
                content = read_document(root, arguments)
            else:
                raise ValueError("Unknown tool.")
            result["result"] = {"content": content}
        except (OSError, ValueError, KeyError, AttributeError, TypeError, zipfile.BadZipFile,
                ElementTree.ParseError, subprocess.SubprocessError) as error:
            message = str(error) if isinstance(error, ValueError) else "Unable to read the file or reach AKI.Gate."
            result["result"] = {"content": [{"type": "text", "text": message}], "isError": True}
    else:
        result["error"] = {"code": -32601, "message": "Method not found"}
    return result


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--workspace", type=Path, default=Path.cwd())
    project = parser.parse_args().workspace.resolve(strict=True)
    for line in sys.stdin:
        try:
            message = json.loads(line)
            if not isinstance(message, dict):
                raise ValueError("Expected a JSON-RPC request")
            response = reply(message, project)
        except (ValueError, AttributeError):
            response = {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid request"}}
        if response is not None:
            print(json.dumps(response, ensure_ascii=False), flush=True)
