#!/usr/bin/env python3
"""Capzo Model Context Protocol (MCP) Server.

This server implements the official Model Context Protocol (MCP) over standard I/O (stdio).
It enables AI Agents—including Adobe Premiere Pro AI Agents, Claude Desktop, Cursor,
and automated video pipelines—to seamlessly transcribe media files into flawless Persian
and multilingual text, custom chunked subtitles (SRT), speaker-separated tracks, and
word-level timestamps.

Key Capabilities:
- capzo_transcribe: Transcribe media with customizable output formats (SRT, plain text,
  speaker tracks, or full JSON) and customizable chunking (word-level for viral Reels/Shorts
  or sentence-level for long-form video).
- capzo_get_speaker_tracks: Automatically separate and extract individual subtitle tracks
  and dialogue for each speaker (ideal for podcasts, interviews, and multi-track video editing).
- capzo_get_subtitles_with_words: High-precision word-level timestamps (start/end in hundredths
  of a second) for viral hook detection, jump-cuts, and karaoke motion graphics.
- capzo_get_job: Retrieve previous transcription results and subtitles by Job ID without
  re-uploading or consuming extra credits.
- capzo_check_balance: Query account balance, subscription plan, and active limits.

Security & Architecture:
- Pure Python standard library (zero pip dependencies required).
- Strict adherence to MCP JSON-RPC 2.0 specifications.
- Safe path resolution, extension whitelisting, and file-size validation (up to 150MB).
- Strict secret masking (API keys and tokens are never printed or leaked).
- Automated non-blocking telemetry & bug reporting to the Capzo error pipeline.

Environment Variables:
- CAPZO_API_KEY: Secret token generated in https://capzo.ir/app/account#api-keys (capzo_live_...)
- CAPZO_API_BASE: Optional override for API root (default: https://capzo.ir/api/v1)

Author: Capzo AI Team
Version: 1.2.0
License: Proprietary / MIT Compatible Client
"""

from __future__ import annotations

import argparse
import json
import mimetypes
import os
import platform
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional

SERVER_NAME = "capzo-mcp"
SERVER_VERSION = "1.2.0"
PROTOCOL_VERSION = "2024-11-05"

DEFAULT_API_BASE = "https://capzo.ir/api/v1"
DEFAULT_BUG_REPORT_URL = "https://capzo.ir/api/plugin/bug-report"
MAX_FILE_SIZE_BYTES = 150 * 1024 * 1024  # 150 Megabytes safety ceiling

ALLOWED_MEDIA_EXTENSIONS = frozenset({
    ".mp3",
    ".wav",
    ".m4a",
    ".aac",
    ".flac",
    ".ogg",
    ".opus",
    ".mp4",
    ".mov",
    ".mkv",
    ".webm",
    ".avi",
    ".ts",
    ".aiff",
    ".aif",
})


def log_debug(message: str) -> None:
    """Write diagnostic messages to stderr to keep stdout strictly clean for JSON-RPC."""
    sys.stderr.write(f"[{SERVER_NAME}] {message}\n")
    sys.stderr.flush()


def sanitize_error_message(msg: str) -> str:
    """Sanitize error messages to avoid leaking API tokens, local file paths, or provider names."""
    if not msg:
        return "Unknown error"
    # Redact Capzo API keys
    cleaned = re.sub(r"capzo_live_[a-zA-Z0-9_-]+", "capzo_live_***REDACTED***", msg)
    # Redact Bearer tokens
    cleaned = re.sub(r"Bearer\s+[a-zA-Z0-9._-]+", "Bearer ***REDACTED***", cleaned, flags=re.IGNORECASE)
    # Redact internal file paths if present
    cleaned = re.sub(r"(/[a-zA-Z0-9._-]+)+/\w+\.py", "internal_module.py", cleaned)
    cleaned = re.sub(r"([a-zA-Z]:\\[a-zA-Z0-9._\-\\]+)\\\w+\.py", "internal_module.py", cleaned)
    return cleaned


def validate_media_file_path(file_path_str: str) -> Path:
    """Securely validate a media file path: existence, regular file, size, and extension."""
    if not file_path_str or not file_path_str.strip():
        raise ValueError("Missing required file_path parameter.")

    resolved = Path(file_path_str.strip()).resolve()

    if not resolved.exists():
        raise FileNotFoundError(f"Media file not found on disk: {resolved.name}")
    if not resolved.is_file():
        raise ValueError(f"Path is not a regular file: {resolved.name}")

    ext = resolved.suffix.lower()
    if ext not in ALLOWED_MEDIA_EXTENSIONS:
        allowed_list = ", ".join(sorted(ALLOWED_MEDIA_EXTENSIONS))
        raise ValueError(
            f"Unsupported file format '{ext}'. Allowed formats: {allowed_list}"
        )

    file_size = resolved.stat().st_size
    if file_size == 0:
        raise ValueError("The provided media file is empty (0 bytes).")
    if file_size > MAX_FILE_SIZE_BYTES:
        max_mb = MAX_FILE_SIZE_BYTES // (1024 * 1024)
        actual_mb = round(file_size / (1024 * 1024), 1)
        raise ValueError(
            f"File size ({actual_mb}MB) exceeds the maximum allowed MCP limit ({max_mb}MB). "
            "Please compress audio or process shorter clips."
        )

    return resolved


class CapzoAPIClient:
    """Client for interacting with Capzo REST endpoints and automated bug reporting."""

    def __init__(
        self,
        api_key: Optional[str] = None,
        api_base: Optional[str] = None,
        bug_report_url: Optional[str] = None,
    ) -> None:
        self.api_key = (api_key or os.environ.get("CAPZO_API_KEY", "")).strip()
        self.api_base = (api_base or os.environ.get("CAPZO_API_BASE", DEFAULT_API_BASE)).rstrip("/")
        self.bug_report_url = bug_report_url or DEFAULT_BUG_REPORT_URL

    def is_configured(self) -> bool:
        """Return True if an API key is configured."""
        return bool(self.api_key)

    def report_bug(
        self,
        error_message: str,
        action: Optional[str] = None,
        context: Optional[Dict[str, Any]] = None,
    ) -> None:
        """Send a non-blocking, sanitized bug report to Capzo central monitoring.

        Never crashes or hangs the MCP server if telemetry fails.
        """
        try:
            payload_context = {
                "os_platform": platform.system(),
                "os_release": platform.release(),
                "python_version": platform.python_version(),
                "server_version": SERVER_VERSION,
            }
            if context:
                for k, v in context.items():
                    if k not in ("api_key", "token", "file_bytes", "data"):
                        payload_context[k] = v

            report_data = {
                "error_message": sanitize_error_message(error_message)[:3500],
                "feature": "mcp_server",
                "action": action or "tool_execution",
                "context": payload_context,
                "plugin_version": f"mcp-{SERVER_VERSION}",
            }

            body = json.dumps(report_data).encode("utf-8")
            req = urllib.request.Request(
                self.bug_report_url,
                data=body,
                headers={
                    "Content-Type": "application/json; charset=utf-8",
                    "User-Agent": f"Capzo-MCP-Telemetry/{SERVER_VERSION}",
                },
                method="POST",
            )
            # Short timeout so bug report never delays responses
            with urllib.request.urlopen(req, timeout=3.5):
                pass
        except Exception:
            # Telemetry failures are strictly non-fatal
            pass

    def request(
        self,
        endpoint: str,
        method: str = "GET",
        data: Optional[bytes] = None,
        headers: Optional[Dict[str, str]] = None,
        timeout: int = 300,
    ) -> Dict[str, Any]:
        """Execute an authenticated HTTP request to the Capzo REST API."""
        if not self.is_configured():
            raise ValueError(
                "Capzo API Key is missing. Please set the CAPZO_API_KEY environment variable "
                "with your secret token (capzo_live_...) from https://capzo.ir/app/account#api-keys."
            )

        url = f"{self.api_base}{endpoint}"
        req_headers = {
            "Authorization": f"Bearer {self.api_key}",
            "User-Agent": f"Capzo-MCP-Client/{SERVER_VERSION} ({platform.system()})",
        }
        if headers:
            req_headers.update(headers)

        req = urllib.request.Request(url, data=data, headers=req_headers, method=method)

        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                raw_bytes = resp.read()
                raw_text = raw_bytes.decode("utf-8")
                return json.loads(raw_text)
        except urllib.error.HTTPError as exc:
            err_body = exc.read().decode("utf-8", errors="replace")
            try:
                parsed = json.loads(err_body)
                error_msg = parsed.get("detail") or parsed.get("message") or err_body
            except Exception:
                error_msg = err_body

            # Report 5xx server errors to Capzo bug tracker
            if exc.code >= 500:
                self.report_bug(
                    f"HTTP {exc.code} during {endpoint}: {error_msg}",
                    action=f"http_{endpoint.replace('/', '_')}",
                    context={"status_code": exc.code},
                )
            raise RuntimeError(f"Capzo API Error [{exc.code}]: {sanitize_error_message(str(error_msg))}") from exc
        except urllib.error.URLError as exc:
            err_str = f"Network connection error to Capzo server: {exc.reason}"
            self.report_bug(err_str, action="connection_error")
            raise RuntimeError(err_str) from exc

    def upload_file_multipart(
        self,
        file_path_str: str,
        *,
        language: str = "fa",
        diarize: bool = False,
        segment_mode: str = "word",
        max_characters_per_line: int = 42,
        display_name: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Validate, package, and upload an audio/video file for AI transcription."""
        resolved_path = validate_media_file_path(file_path_str)

        filename = resolved_path.name
        mime_type, _ = mimetypes.guess_type(str(resolved_path))
        if not mime_type:
            mime_type = "audio/mpeg"

        with open(resolved_path, "rb") as fh:
            file_bytes = fh.read()

        boundary = f"----CapzoMCPBoundary{uuid.uuid4().hex}"
        body = bytearray()

        def add_field(name: str, value: str) -> None:
            body.extend(f"--{boundary}\r\n".encode("utf-8"))
            body.extend(f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode("utf-8"))
            body.extend(f"{value}\r\n".encode("utf-8"))

        clean_lang = (language or "fa").strip().lower()
        clean_mode = segment_mode if segment_mode in {"word", "sentence", "character"} else "word"
        clean_max_chars = max(15, min(120, int(max_characters_per_line)))

        add_field("language", clean_lang)
        add_field("diarize", "true" if diarize else "false")
        add_field("segment_mode", clean_mode)
        add_field("max_characters_per_line", str(clean_max_chars))
        if display_name:
            add_field("display_name", display_name[:120])

        body.extend(f"--{boundary}\r\n".encode("utf-8"))
        body.extend(f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'.encode("utf-8"))
        body.extend(f"Content-Type: {mime_type}\r\n\r\n".encode("utf-8"))
        body.extend(file_bytes)
        body.extend(b"\r\n")
        body.extend(f"--{boundary}--\r\n".encode("utf-8"))

        headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"}
        return self.request("/transcribe", method="POST", data=bytes(body), headers=headers)


class CapzoMCPServer:
    """Model Context Protocol (MCP) JSON-RPC 2.0 stdio Server."""

    def __init__(self, client: CapzoAPIClient) -> None:
        self.client = client

    def send_response(self, response_dict: Dict[str, Any]) -> None:
        """Send a JSON-RPC message to stdout followed by newline."""
        payload = json.dumps(response_dict, ensure_ascii=False)
        sys.stdout.write(payload + "\n")
        sys.stdout.flush()

    def send_error(self, req_id: Any, code: int, message: str) -> None:
        """Send a standardized JSON-RPC error response."""
        self.send_response({
            "jsonrpc": "2.0",
            "id": req_id,
            "error": {"code": code, "message": sanitize_error_message(message)},
        })

    def get_tools_list(self) -> List[Dict[str, Any]]:
        """Return the comprehensive MCP tools schema available to AI Agents."""
        return [
            {
                "name": "capzo_transcribe",
                "description": (
                    "Transcribe audio or video media into accurate Persian or multilingual text and SRT subtitles "
                    "using the Capzo AI Speech Engine. Supports multiple output formats (SRT, plain text, speaker tracks, "
                    "or structured JSON) and customizable chunking (word-level for fast viral Reels/Shorts or sentence-level "
                    "for long-form video). Perfect for Adobe Premiere Pro timeline captions and automated video workflows."
                ),
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Full absolute path to the audio or video file on disk (e.g. mp3, wav, mp4, mov, m4a, webm).",
                        },
                        "language": {
                            "type": "string",
                            "description": "Spoken language code: 'fa' for Persian, 'en' for English, or 'auto' for auto-detection.",
                            "default": "fa",
                        },
                        "diarize": {
                            "type": "boolean",
                            "description": "Whether to detect, differentiate, and separate distinct speakers in the audio.",
                            "default": False,
                        },
                        "segment_mode": {
                            "type": "string",
                            "enum": ["word", "sentence", "character"],
                            "description": (
                                "Chunking segmentation strategy: 'word' (punchy short chunks for Instagram Reels & TikTok), "
                                "'sentence' (grammatical complete sentences for podcasts and tutorials), or 'character'."
                            ),
                            "default": "word",
                        },
                        "max_characters_per_line": {
                            "type": "integer",
                            "description": "Maximum characters per subtitle line (15 to 120). Use 18-28 for viral short-form captions.",
                            "default": 42,
                        },
                        "output_format": {
                            "type": "string",
                            "enum": ["all", "srt", "text", "speakers", "json"],
                            "description": (
                                "Desired output format: 'all' (comprehensive summary + transcript + SRT), 'srt' (clean raw SRT for video editors), "
                                "'text' (pure transcript text), 'speakers' (dialogue organized by speaker with individual tracks), or 'json' (full structured data)."
                            ),
                            "default": "all",
                        },
                    },
                    "required": ["file_path"],
                },
            },
            {
                "name": "capzo_get_speaker_tracks",
                "description": (
                    "Transcribe multi-speaker media and automatically separate subtitle tracks and dialogue by speaker. "
                    "Essential for podcasts, interviews, panel discussions, and Premiere Pro multi-track captioning "
                    "(e.g. placing Speaker 1 on Track 1 and Speaker 2 on Track 2 with custom styling)."
                ),
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Full absolute path to the multi-speaker audio or video file.",
                        },
                        "language": {
                            "type": "string",
                            "description": "Spoken language code ('fa', 'en', 'auto').",
                            "default": "fa",
                        },
                        "segment_mode": {
                            "type": "string",
                            "enum": ["sentence", "word", "character"],
                            "description": "Chunking mode ('sentence' recommended for multi-speaker podcasts).",
                            "default": "sentence",
                        },
                        "max_characters_per_line": {
                            "type": "integer",
                            "description": "Maximum characters per subtitle line (15 to 120).",
                            "default": 42,
                        },
                    },
                    "required": ["file_path"],
                },
            },
            {
                "name": "capzo_get_subtitles_with_words",
                "description": (
                    "Transcribe media and extract high-precision word-level timestamps (start and end times in hundredths of a second) "
                    "along with full SRT text. Essential for viral hook detection, automated reels cutting, and "
                    "karaoke-style motion graphics in Adobe Premiere Pro and After Effects."
                ),
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Full absolute path to the media file on disk.",
                        },
                        "language": {
                            "type": "string",
                            "description": "Language code: 'fa' (Persian), 'en' (English), or 'auto'.",
                            "default": "fa",
                        },
                        "segment_mode": {
                            "type": "string",
                            "enum": ["word", "sentence", "character"],
                            "description": "Chunking mode ('word' for fast viral rhythm).",
                            "default": "word",
                        },
                        "max_characters_per_line": {
                            "type": "integer",
                            "description": "Maximum characters per subtitle line (15 to 120).",
                            "default": 42,
                        },
                    },
                    "required": ["file_path"],
                },
            },
            {
                "name": "capzo_get_job",
                "description": (
                    "Retrieve previously processed transcription results, SRT subtitles, and speaker tracks by Job ID "
                    "without re-uploading the file or consuming any extra credits."
                ),
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "job_id": {
                            "type": "integer",
                            "description": "The integer ID of the transcription task to fetch.",
                        },
                        "output_format": {
                            "type": "string",
                            "enum": ["all", "srt", "text", "speakers", "json"],
                            "description": "Desired format: 'all', 'srt', 'text', 'speakers', or 'json'.",
                            "default": "all",
                        },
                    },
                    "required": ["job_id"],
                },
            },
            {
                "name": "capzo_check_balance",
                "description": "Check current Capzo account subscription plan, active status, and remaining minutes balance.",
                "inputSchema": {
                    "type": "object",
                    "properties": {},
                },
            },
        ]

    def _format_speaker_breakdown(self, result: Dict[str, Any]) -> str:
        """Format dialogue and separate speaker tracks cleanly."""
        tracks = result.get("speaker_tracks") or []
        lines = [
            f"Job ID: {result.get('job_id')}",
            f"Duration: {result.get('duration_seconds')} seconds",
            f"Detected Speakers: {len(tracks) if tracks else (2 if result.get('diarize') else 1)}",
            "",
            "=== Dialogue by Speaker ===",
        ]

        if tracks:
            for track in tracks:
                label = track.get("label") or f"Speaker {track.get('speaker_id', '?')}"
                lines.append(f"\n[{label}]")
                lines.append(str(track.get("transcript") or "").strip())
            lines.append("\n=== Individual Speaker Subtitle Tracks ===")
            for track in tracks:
                label = track.get("label") or f"Speaker {track.get('speaker_id', '?')}"
                lines.append(f"\n--- {label} (SRT Track) ---")
                lines.append(str(track.get("srt") or "").strip())
        else:
            lines.append(str(result.get("transcript") or "").strip())
            lines.append("\n=== Subtitles (SRT) ===")
            lines.append(str(result.get("srt") or "").strip())

        return "\n".join(lines)

    def handle_tool_call(self, name: str, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Dispatch and execute an MCP tool invocation."""
        if name == "capzo_check_balance":
            res = self.client.request("/user/me", method="GET")
            user = res.get("user", {})
            rem = user.get("credits_remaining", 0)
            unlimited = user.get("credit_unlimited")
            info_lines = [
                f"Capzo User: {user.get('username')}",
                f"Subscription Plan: {user.get('subscription_plan', 'None')}",
                f"Remaining Balance: {'Unlimited (' + str(round(rem, 1)) + ' mins)' if unlimited else str(round(rem, 1)) + ' minutes'}",
                f"Consumed Credits: {round(float(user.get('credits_used', 0)), 1)} minutes",
                f"Days Remaining: {user.get('subscription_days_remaining', 0)} days",
                f"Active Account: {user.get('can_transcribe', False)}",
            ]
            return [{"type": "text", "text": "\n".join(info_lines)}]

        if name == "capzo_get_job":
            job_id = int(arguments.get("job_id", 0))
            if job_id <= 0:
                raise ValueError("Invalid job_id: must be a positive integer.")
            out_fmt = str(arguments.get("output_format", "all")).lower().strip()

            result = self.client.request(f"/jobs/{job_id}", method="GET")
            if out_fmt == "srt":
                return [{"type": "text", "text": str(result.get("srt", ""))}]
            if out_fmt == "text":
                return [{"type": "text", "text": str(result.get("transcript", ""))}]
            if out_fmt == "speakers":
                return [{"type": "text", "text": self._format_speaker_breakdown(result)}]
            if out_fmt == "json":
                return [{"type": "text", "text": json.dumps(result, ensure_ascii=False, indent=2)}]

            # Default: 'all'
            overview = [
                f"Job ID: {result.get('job_id')}",
                f"Filename: {result.get('filename')}",
                f"Duration: {result.get('audio_duration_secs')} seconds",
                f"Status: {result.get('status')}",
                f"Credits Charged: {result.get('credits_charged')} minutes",
                "",
                "=== Full Transcript ===",
                str(result.get("transcript", "")),
                "",
                "=== Subtitles (SRT Format) ===",
                str(result.get("srt", "")),
            ]
            tracks = result.get("speaker_tracks") or []
            if tracks:
                overview.append("")
                overview.append("=== Speaker Tracks ===")
                for track in tracks:
                    overview.append(f"\n--- {track.get('label', 'Speaker')} ---")
                    overview.append(str(track.get("srt", "")).strip())

            return [{"type": "text", "text": "\n".join(overview)}]

        if name == "capzo_get_speaker_tracks":
            file_path = str(arguments.get("file_path", "")).strip()
            language = str(arguments.get("language", "fa")).strip() or "fa"
            segment_mode = str(arguments.get("segment_mode", "sentence")).strip() or "sentence"
            max_chars = int(arguments.get("max_characters_per_line", 42))

            result = self.client.upload_file_multipart(
                file_path,
                language=language,
                diarize=True,
                segment_mode=segment_mode,
                max_characters_per_line=max_chars,
            )
            return [{"type": "text", "text": self._format_speaker_breakdown(result)}]

        if name == "capzo_get_subtitles_with_words":
            file_path = str(arguments.get("file_path", "")).strip()
            language = str(arguments.get("language", "fa")).strip() or "fa"
            segment_mode = str(arguments.get("segment_mode", "word")).strip() or "word"
            max_chars = int(arguments.get("max_characters_per_line", 42))

            result = self.client.upload_file_multipart(
                file_path,
                language=language,
                diarize=False,
                segment_mode=segment_mode,
                max_characters_per_line=max_chars,
            )
            words = result.get("words") or []
            structured_payload = {
                "job_id": result.get("job_id"),
                "duration_seconds": result.get("duration_seconds"),
                "credits_charged": result.get("credits_charged"),
                "credits_remaining": result.get("credits_remaining"),
                "words_count": len(words),
                "transcript": result.get("transcript"),
                "srt": result.get("srt"),
                "words": words,
            }
            return [{"type": "text", "text": json.dumps(structured_payload, ensure_ascii=False, indent=2)}]

        if name == "capzo_transcribe":
            file_path = str(arguments.get("file_path", "")).strip()
            language = str(arguments.get("language", "fa")).strip() or "fa"
            diarize = bool(arguments.get("diarize", False))
            segment_mode = str(arguments.get("segment_mode", "word")).strip() or "word"
            max_chars = int(arguments.get("max_characters_per_line", 42))
            out_fmt = str(arguments.get("output_format", "all")).lower().strip() or "all"

            result = self.client.upload_file_multipart(
                file_path,
                language=language,
                diarize=diarize,
                segment_mode=segment_mode,
                max_characters_per_line=max_chars,
            )

            if out_fmt == "srt":
                return [{"type": "text", "text": str(result.get("srt", ""))}]
            if out_fmt == "text":
                return [{"type": "text", "text": str(result.get("transcript", ""))}]
            if out_fmt == "speakers":
                return [{"type": "text", "text": self._format_speaker_breakdown(result)}]
            if out_fmt == "json":
                return [{"type": "text", "text": json.dumps(result, ensure_ascii=False, indent=2)}]

            # Default: 'all'
            output_sections = [
                f"Job ID: {result.get('job_id')}",
                f"Duration: {result.get('duration_seconds')} seconds",
                f"Charged Credits: {result.get('credits_charged')} minutes",
                f"Remaining Credits: {result.get('credits_remaining')} minutes",
                f"Chunking Mode: {segment_mode} (max {max_chars} chars/line)",
            ]
            if diarize:
                tracks = result.get("speaker_tracks") or []
                output_sections.append(f"Speakers Identified: {len(tracks) if tracks else 2}")

            output_sections.extend([
                "",
                "=== Full Transcript ===",
                str(result.get("transcript", "")),
                "",
                "=== Subtitle (SRT Format) ===",
                str(result.get("srt", "")),
            ])

            tracks = result.get("speaker_tracks") or []
            if diarize and tracks:
                output_sections.append("")
                output_sections.append("=== Speaker Tracks ===")
                for track in tracks:
                    output_sections.append(f"\n--- {track.get('label', 'Speaker')} ---")
                    output_sections.append(str(track.get("srt", "")).strip())

            return [{"type": "text", "text": "\n".join(output_sections)}]

        raise ValueError(f"Unknown MCP tool requested: '{name}'")

    def run(self) -> None:
        """Main stdio read loop for JSON-RPC messages."""
        log_debug(f"Starting {SERVER_NAME} v{SERVER_VERSION} on stdio...")

        for raw_line in sys.stdin:
            line = raw_line.strip()
            if not line:
                continue

            try:
                message = json.loads(line)
            except Exception as exc:
                self.send_error(None, -32700, f"JSON Parse error: {exc}")
                continue

            req_id = message.get("id")
            method = message.get("method")
            params = message.get("params") or {}

            # Handle MCP Handshake
            if method == "initialize":
                self.send_response({
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {
                        "protocolVersion": PROTOCOL_VERSION,
                        "capabilities": {
                            "tools": {},
                        },
                        "serverInfo": {
                            "name": SERVER_NAME,
                            "version": SERVER_VERSION,
                        },
                    },
                })
            elif method == "notifications/initialized":
                # Client initialization acknowledgement
                pass
            elif method == "ping":
                self.send_response({
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {},
                })
            elif method == "tools/list":
                self.send_response({
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {
                        "tools": self.get_tools_list(),
                    },
                })
            elif method == "tools/call":
                tool_name = params.get("name", "")
                tool_args = params.get("arguments") or {}
                try:
                    content = self.handle_tool_call(tool_name, tool_args)
                    self.send_response({
                        "jsonrpc": "2.0",
                        "id": req_id,
                        "result": {
                            "content": content,
                            "isError": False,
                        },
                    })
                except Exception as exc:
                    log_debug(f"Tool execution failed for '{tool_name}': {exc}")
                    # Dispatch non-blocking telemetry report on unhandled crashes
                    self.client.report_bug(
                        f"MCP Tool '{tool_name}' failed: {exc}",
                        action=f"mcp_tool_{tool_name}",
                        context={"tool": tool_name},
                    )
                    self.send_response({
                        "jsonrpc": "2.0",
                        "id": req_id,
                        "result": {
                            "content": [{"type": "text", "text": f"Error: {sanitize_error_message(str(exc))}"}],
                            "isError": True,
                        },
                    })
            else:
                if req_id is not None:
                    self.send_error(req_id, -32601, f"Method not supported: '{method}'")


def main() -> None:
    """Parse CLI options and run the MCP server."""
    parser = argparse.ArgumentParser(
        description="Capzo Model Context Protocol (MCP) stdio server for AI video agents.",
    )
    parser.add_argument(
        "--api-key",
        dest="api_key",
        default=None,
        help="Capzo API Key (capzo_live_...). Defaults to CAPZO_API_KEY environment variable.",
    )
    parser.add_argument(
        "--api-base",
        dest="api_base",
        default=None,
        help=f"Capzo API Base URL (defaults to {DEFAULT_API_BASE}).",
    )
    args = parser.parse_args()

    client = CapzoAPIClient(api_key=args.api_key, api_base=args.api_base)
    server = CapzoMCPServer(client)
    server.run()


if __name__ == "__main__":
    main()
