"""
Tool: parse_all_programs
Takes a manifest.json (from mainframe-ingest-mcp) and parses every
COBOL program in it, optionally generating AI summaries.
"""

import json
import logging
from pathlib import Path
from .parser import parse_cobol_file

logger = logging.getLogger(__name__)


async def parse_all_programs(
    manifest_path: str,
    output_dir: str,
    ai_summaries: bool = True,
    api_key: str | None = None,
    provider: str = "anthropic",
    model: str | None = None,
    base_url: str | None = None,
    max_ai_programs: int = 20,
) -> dict:
    """
    Parse all COBOL programs listed in a manifest.json.

    Args:
        manifest_path:    Path to manifest.json from mainframe-ingest-mcp.
        output_dir:       Directory to write individual program JSON files.
        ai_summaries:     Whether to call an LLM for business logic summaries.
        api_key:          API key for the chosen provider.
        provider:         anthropic | openai | groq | ollama | custom. Default: anthropic.
        model:            Model override. Uses provider default if not set.
        base_url:         Custom base URL for 'custom' provider.
        max_ai_programs:  Cap on AI calls to control cost (default 20).

    Returns:
        Summary dict with stats and list of output files.
    """
    manifest_file = Path(manifest_path)
    if not manifest_file.exists():
        return {"status": "error", "message": f"Manifest not found: {manifest_path}"}

    with open(manifest_file) as f:
        manifest = json.load(f)

    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    programs = manifest.get("cobol_programs", [])
    if not programs:
        return {"status": "error", "message": "No cobol_programs found in manifest"}

    results  = []
    errors   = []
    ai_count = 0

    for prog in programs:
        file_path = prog.get("path") or prog.get("absolute_path") or prog.get("file")
        if not file_path:
            continue

        logger.info("Parsing %s", file_path)

        try:
            parsed = parse_cobol_file(file_path)

            if parsed.get("status") == "error":
                errors.append({"file": file_path, "error": parsed["message"]})
                continue

            # AI summary
            if ai_summaries and ai_count < max_ai_programs:
                from .summariser import summarise_with_ai
                ai_result = await summarise_with_ai(
                    file_path, parsed,
                    api_key=api_key,
                    provider=provider,
                    model=model,
                    base_url=base_url,
                )
                try:
                    ai_data = json.loads(ai_result)
                    parsed["business_logic_summary"]["ai_summary"] = ai_data
                except (json.JSONDecodeError, TypeError):
                    parsed["business_logic_summary"]["ai_summary"] = ai_result
                ai_count += 1

            # Write per-program JSON
            out_file = output_path / f"{parsed['program']}.json"
            with open(out_file, "w") as f:
                json.dump(parsed, f, indent=2)

            results.append({
                "program":    parsed["program"],
                "file":       file_path,
                "output":     str(out_file),
                "lines":      parsed["line_count"],
                "paragraphs": parsed["procedure_division"]["paragraph_count"],
                "sql_count":  len(parsed["sql_statements"]),
                "cics_count": len(parsed["cics_commands"]),
                "complexity": parsed["business_logic_summary"]["estimated_complexity"],
                "ai_summary": parsed["business_logic_summary"].get("ai_summary") is not None,
            })

        except Exception as e:
            logger.error("Failed to parse %s: %s", file_path, e)
            errors.append({"file": file_path, "error": str(e)})

    index = {
        "total_programs": len(programs),
        "parsed_ok":      len(results),
        "errors":         len(errors),
        "ai_summaries":   ai_count,
        "provider":       provider,
        "model":          model,
        "output_dir":     str(output_path),
        "programs":       results,
        "error_list":     errors,
    }
    with open(output_path / "_index.json", "w") as f:
        json.dump(index, f, indent=2)

    return index
