"""
cobol-parser-mcp
MCP server that parses COBOL programs and extracts structured data
plus AI-powered business logic summaries (any LLM provider).

Tools:
  tool_parse_cobol_file     — parse a single COBOL file
  tool_summarise_with_ai    — generate AI summary for a single program
  tool_parse_all_programs   — parse all programs from a manifest.json
"""

import json
import logging
from mcp.server.fastmcp import FastMCP

from cobol_parser_mcp.tools.parser import parse_cobol_file
from cobol_parser_mcp.tools.summariser import summarise_with_ai
from cobol_parser_mcp.tools.batch import parse_all_programs

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

mcp = FastMCP("cobol-parser-mcp")


@mcp.tool()
def tool_parse_cobol_file(file_path: str) -> str:
    """
    Parse a single COBOL source file and extract structured data.

    Extracts IDENTIFICATION, DATA, and PROCEDURE divisions, all embedded
    SQL statements, all CICS commands, and a business logic summary.
    No API key needed — pure parsing only.

    Args:
        file_path: Absolute path to a .cbl or .cob file.

    Returns:
        JSON string with full parsed structure.
    """
    logger.info("tool_parse_cobol_file: %s", file_path)
    return json.dumps(parse_cobol_file(file_path), indent=2)


@mcp.tool()
async def tool_summarise_with_ai(
    file_path: str,
    parsed_json: str,
    provider: str = "anthropic",
    api_key: str = "",
    model: str = "",
    base_url: str = "",
) -> str:
    """
    Generate an AI-powered business logic summary for a COBOL program.

    Supported providers:
      anthropic → Claude (default: claude-sonnet-4-20250514)
      openai    → GPT-4o (default: gpt-4o)
      groq      → Llama3 (default: llama3-70b-8192) — fast and cheap
      ollama    → local models (default: llama3) — no API key needed
      custom    → any OpenAI-compatible endpoint, pass base_url

    API keys fall back to env vars: ANTHROPIC_API_KEY, OPENAI_API_KEY, GROQ_API_KEY.

    Args:
        file_path:   Absolute path to the .cbl or .cob file.
        parsed_json: JSON string returned by tool_parse_cobol_file.
        provider:    LLM provider. Default: anthropic.
        api_key:     API key (optional if env var is set).
        model:       Model override (optional — uses provider default).
        base_url:    Base URL for custom/self-hosted providers.

    Returns:
        JSON string with purpose, business_domain, key_operations, etc.
    """
    logger.info("tool_summarise_with_ai: %s provider=%s", file_path, provider)
    try:
        parsed = json.loads(parsed_json)
    except json.JSONDecodeError:
        return json.dumps({"error": "Invalid parsed_json"})

    return await summarise_with_ai(
        file_path, parsed,
        api_key=api_key or None,
        provider=provider,
        model=model or None,
        base_url=base_url or None,
    )


@mcp.tool()
async def tool_parse_all_programs(
    manifest_path: str,
    output_dir: str,
    ai_summaries: bool = True,
    provider: str = "anthropic",
    api_key: str = "",
    model: str = "",
    base_url: str = "",
    max_ai_programs: int = 20,
) -> str:
    """
    Parse all COBOL programs listed in a manifest.json from mainframe-ingest-mcp.

    For each program: parses structure, optionally generates AI summary,
    writes <PROGRAM>.json to output_dir, and writes _index.json summary.

    Supported providers: anthropic, openai, groq, ollama, custom.
    Set max_ai_programs=0 to skip AI summaries entirely (no API key needed).

    Args:
        manifest_path:    Path to manifest.json from mainframe-ingest-mcp.
        output_dir:       Directory to write parsed program JSON files.
        ai_summaries:     Generate AI summaries. Default: true.
        provider:         LLM provider. Default: anthropic.
        api_key:          API key (optional if env var is set).
        model:            Model override (optional).
        base_url:         Base URL for custom providers.
        max_ai_programs:  Max AI calls to make. Default: 20.

    Returns:
        JSON string with parse stats and list of output files.
    """
    logger.info("tool_parse_all_programs: %s", manifest_path)
    result = await parse_all_programs(
        manifest_path=manifest_path,
        output_dir=output_dir,
        ai_summaries=ai_summaries,
        api_key=api_key or None,
        provider=provider,
        model=model or None,
        base_url=base_url or None,
        max_ai_programs=max_ai_programs,
    )
    return json.dumps(result, indent=2)


def main():
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()
