import json
from pathlib import Path
import csv

OPENAPI_PATH = "../extra/openapi_clean.json"
ENDPOINTS_PATH = "../extra/endpoints_spec_en.csv"
OUTPUT_PATH = "../data/tools_autogen.py"


def load_endpoint_list(path):
    with open(path, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        next(reader, None)  # skip header
        return [row[0] for row in reader]


def generate_code(endpoints, spec):
    ops = []
    for path in endpoints:
        if path not in spec.get('paths', {}):
            continue
        for method, details in spec['paths'][path].items():
            op_id = details.get('operationId')
            description = details.get('description', '').strip().replace('"', '\\"').replace('\n', ' ')
            if not op_id:
                continue
            endpoint_key = path.lstrip('/')
            ops.append((op_id, description, endpoint_key))

    lines = []
    # Imports
    lines.append('from mcp.server import FastMCP')
    lines.append('from mcp.server.fastmcp import Context')
    lines.append('')

    # Request model imports
    for op_id, _, _ in ops:
        lines.append(f'from .request_models import {op_id}Request')
    lines.append('')

    # Response model imports
    for op_id, _, _ in ops:
        lines.append(f'from .response_models import {op_id}200Response')
    lines.append('')

    # register_all_tools function
    lines.append('def register_all_tools(server: FastMCP, _call_endpoint):')
    for op_id, description, endpoint_key in ops:
        lines.append(f'    @server.tool(name="{op_id}",')
        lines.append(f'                 description="{description}")')
        lines.append(f'    async def {op_id}(params: {op_id}Request, ctx: Context) -> {op_id}200Response:')
        lines.append(f'        return await _call_endpoint("{endpoint_key}", params, {op_id}200Response, ctx)')
        lines.append('')

    return "\n".join(lines)


def main():
    endpoints = load_endpoint_list(ENDPOINTS_PATH)
    with open(OPENAPI_PATH, encoding='utf-8') as f:
        spec = json.load(f)

    code = generate_code(endpoints, spec)
    header = '# AUTOGENERATED FILE - DO NOT EDIT MANUALLY' + '\n\n'
    Path(OUTPUT_PATH).write_text(header + code, encoding='utf-8')


if __name__ == '__main__':
    main()
