"""
AST Analysis Module
"""

import json
from pathlib import Path
from typing import List, Dict

from ..utils.shell import run_command
from ..utils.logger import log_progress
from ..utils.fs import save_json

class ASTAnalyzer:
    """Analyze JavaScript files using AST parsing"""
    
    def __init__(self, output_dir: Path):
        self.output_dir = output_dir
        self.ast_script = Path(__file__).parent.parent.parent / "scripts" / "ast_parser.js"
    
    def analyze_file(self, js_file_path: str) -> Dict:
        """Analyze a single JavaScript file using AST"""
        try:
            # Run Node.js AST parser
            success, stdout, stderr = run_command([
                "node", str(self.ast_script), js_file_path
            ])
            
            if not success:
                return {
                    'filename': Path(js_file_path).name,
                    'status': 'failed',
                    'error': stderr,
                    'endpoints': [],
                    'sinks': [],
                    'functions': [],
                    'variables': []
                }
            
            # Load AST results
            ast_output_file = js_file_path.replace('.js', '_ast.json')
            
            if Path(ast_output_file).exists():
                with open(ast_output_file, 'r') as f:
                    ast_results = json.load(f)
                
                # Clean up temporary file
                Path(ast_output_file).unlink(missing_ok=True)
                
                return ast_results
            else:
                return {
                    'filename': Path(js_file_path).name,
                    'status': 'no_output',
                    'endpoints': [],
                    'sinks': [],
                    'functions': [],
                    'variables': []
                }
                
        except Exception as e:
            return {
                'filename': Path(js_file_path).name,
                'status': 'error',
                'error': str(e),
                'endpoints': [],
                'sinks': [],
                'functions': [],
                'variables': []
            }
    
    def analyze_files(self, js_files: List[Dict]) -> Dict[str, List]:
        """Analyze multiple JavaScript files using AST"""
        log_progress("Running AST analysis on JavaScript files")
        
        all_results = {
            'endpoints': [],
            'sinks': [],
            'functions': [],
            'variables': [],
            'metadata': []
        }
        
        analyzed_count = 0
        
        for js_file in js_files:
            if js_file.get('status') != 'success' or not js_file.get('filepath'):
                continue
            
            ast_results = self.analyze_file(js_file['filepath'])
            
            # Merge results
            for category in ['endpoints', 'sinks', 'functions', 'variables']:
                if category in ast_results:
                    all_results[category].extend(ast_results[category])
            
            # Store metadata
            if 'metadata' in ast_results:
                all_results['metadata'].append(ast_results['metadata'])
            
            analyzed_count += 1
            
            if analyzed_count % 10 == 0:
                log_progress(f"AST analyzed {analyzed_count}/{len(js_files)} files")
        
        # Save results
        save_json(all_results, self.output_dir / "ast_analysis.json")
        
        total_findings = (
            len(all_results['endpoints']) + 
            len(all_results['sinks']) + 
            len(all_results['functions'])
        )
        
        log_progress(f"AST analysis complete: {total_findings} findings from {analyzed_count} files")
        
        return all_results