"""Read-only MCP log search. Requires Python 3.11+ and mcp==2.3.0."""
import os
import re
import sqlite3
from pathlib import Path
from typing import Annotated

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from pydantic import Field

mcp = MCPServer("Service logs")
SERVICE = os.environ["ALLOWED_SERVICE"]
DATABASE = Path(os.environ["LOG_DB_PATH"]).resolve().as_uri() + "?mode=ro"
SECRET = re.compile(r"(?i)\b(token|password|api[_-]?key|authorization)\s*[:=]\s*(?:bearer\s+)?\S+")


@mcp.tool()
def search_logs(
    service: str,
    query: Annotated[str, Field(min_length=1, max_length=500)],
    limit: Annotated[int, Field(ge=1, le=100)] = 20,
) -> list[dict[str, str]]:
    """Search the service authorized by this connection. Returns newest first."""
    if service != SERVICE:
        raise ToolError("Service is outside this connection's scope")
    with sqlite3.connect(DATABASE, uri=True, timeout=5) as connection:
        connection.row_factory = sqlite3.Row
        rows = connection.execute(
            "SELECT timestamp, level, message FROM logs "
            "WHERE service = ? AND instr(lower(message), lower(?)) > 0 "
            "ORDER BY timestamp DESC LIMIT ?",
            (SERVICE, query, limit),
        ).fetchall()
    return [
        {"timestamp": row["timestamp"], "level": row["level"],
         "message": SECRET.sub(r"\1=[REDACTED]", row["message"])[:2000]}
        for row in rows
    ]


if __name__ == "__main__":
    mcp.run(transport="stdio")
