"""
cobol-parser-mcp
MCP server that parses COBOL mainframe programs and extracts structured data
plus AI-powered business logic summaries.

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

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 DIVISION (program ID, author, date)
    - DATA DIVISION (working storage variables, copybook references)
    - PROCEDURE DIVISION (all paragraphs with line ranges)
    - Embedded SQL (SELECT/INSERT/UPDATE/DELETE with tables and columns)
    - Embedded CICS (SEND/RECEIVE MAP, LINK, XCTL, READ, WRITE)
    - Business logic summary (tables read/written, screens, complexity)

    AI summary field will be null — call tool_summarise_with_ai to populate it.

    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)
    result = parse_cobol_file(file_path)
    return json.dumps(result, indent=2)


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

    Sends the PROCEDURE DIVISION to Claude and returns a structured summary:
    - purpose: what the program does in plain English
    - business_domain: e.g. Business Entity Registration, Payroll Processing
    - user_facing: whether this is an online CICS screen program
    - key_operations: list of 3-5 key things the program does
    - modernization_notes: hints for the developer modernizing this to REST API

    Args:
        file_path:   Absolute path to the .cbl or .cob file.
        parsed_json: JSON string returned by tool_parse_cobol_file.
        api_key:     Anthropic API key (optional — falls back to ANTHROPIC_API_KEY env var).

    Returns:
        JSON string with the AI summary fields.
    """
    logger.info("tool_summarise_with_ai: %s", file_path)
    try:
        parsed = json.loads(parsed_json)
    except json.JSONDecodeError:
        return json.dumps({"error": "Invalid parsed_json — must be output of tool_parse_cobol_file"})

    result = await summarise_with_ai(file_path, parsed, api_key or None)
    return result


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

    For each program:
    1. Parses the COBOL file (divisions, SQL, CICS, paragraphs)
    2. Optionally generates an AI business logic summary (Claude API)
    3. Writes a <PROGRAM_NAME>.json file to output_dir
    4. Writes a _index.json summary to output_dir

    Args:
        manifest_path:    Path to manifest.json produced by mainframe-ingest-mcp.
        output_dir:       Directory to write parsed program JSON files.
        ai_summaries:     Whether to generate AI summaries (default: true).
        api_key:          Anthropic API key (optional — falls back to env var).
        max_ai_programs:  Max number of AI summary calls to make (default: 20).
                          Set to 0 to disable AI summaries entirely.

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


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


if __name__ == "__main__":
    main()
