"""
LinkFinder Integration Module
"""

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 LinkFinderIntegration:
    """Integrate with LinkFinder tool"""
    
    def __init__(self, output_dir: Path):
        self.output_dir = output_dir
    
    def run_linkfinder(self, js_files: List[Dict]) -> List[Dict]:
        """Run LinkFinder on JavaScript files"""
        log_progress("Running LinkFinder on JavaScript files")
        
        endpoints = []
        
        for js_file in js_files:
            if js_file.get('status') != 'success' or not js_file.get('filepath'):
                continue
            
            try:
                # Run linkfinder on the file
                success, stdout, stderr = run_command([
                    "python3", "-m", "linkfinder", 
                    "-i", js_file['filepath'],
                    "-o", "cli"
                ])
                
                if success and stdout:
                    # Parse linkfinder output
                    for line in stdout.split('\n'):
                        line = line.strip()
                        if line and not line.startswith('['):
                            endpoints.append({
                                'url': line,
                                'source_file': Path(js_file['filepath']).name,
                                'tool': 'linkfinder',
                                'confidence': 'medium'
                            })
                
            except Exception as e:
                log_progress(f"Warning: LinkFinder failed for {js_file['filepath']} - {e}")
        
        # Save results
        save_json(endpoints, self.output_dir / "linkfinder_results.json")
        
        log_progress(f"LinkFinder found {len(endpoints)} endpoints")
        
        return endpoints