#!/usr/bin/env python3
"""
Python AST parser for MNE documentation extraction.
Communicates with TypeScript via stdin/stdout JSON.
"""

import ast
import json
import sys
import traceback
from typing import Optional, List, Dict, Any
from ast_extractor import extract_symbol, find_symbols, parse_file, extract_cross_references

def main():
    """Main entry point - read command from stdin, write result to stdout."""
    # Ensure stdout is using utf-8
    sys.stdout.reconfigure(encoding='utf-8')
    sys.stdin.reconfigure(encoding='utf-8')

    try:
        # Read all input from stdin
        input_data = sys.stdin.read()
        if not input_data:
            return

        command = json.loads(input_data)
        action = command.get('action')
        
        result = None
        
        if action == 'parse_file':
            result = parse_file(
                command['source'],
                command.get('moduleName', ''),
                command.get('fileUrl', '')
            )
        elif action == 'extract_symbol':
            result = extract_symbol(
                command['source'],
                command['symbolName'],
                command.get('moduleName', ''),
                command.get('fileUrl', '')
            )
        elif action == 'find_symbols':
            result = find_symbols(
                command['source'],
                command['query'],
                command.get('moduleName', ''),
                command.get('maxResults', 20)
            )
        elif action == 'extract_cross_references':
            result = extract_cross_references(
                command['source'],
                command['symbolName'],
                command.get('moduleName', '')
            )
        else:
            result = {'error': f'Unknown action: {action}'}
        
        json.dump({'success': True, 'data': result}, sys.stdout)
    
    except Exception as e:
        # Capture full traceback for debugging
        tb = traceback.format_exc()
        json.dump({'success': False, 'error': str(e), 'traceback': tb}, sys.stdout)

if __name__ == '__main__':
    main()
