import subprocess
import os
import sys
from web.config import Config

class EtlService:
    @staticmethod
    def run_script(script_name, args=None):
        """
        Executes an ETL script located in the ETL directory.
        Returns (success, message)
        """
        script_path = os.path.join(Config.BASE_DIR, 'ETL', script_name)
        
        if not os.path.exists(script_path):
            return False, f"Script not found: {script_path}"
            
        try:
            # Use the same python interpreter
            python_exe = sys.executable
            
            cmd = [python_exe, script_path]
            if args:
                cmd.extend(args)
            
            result = subprocess.run(
                cmd,
                cwd=Config.BASE_DIR,
                capture_output=True,
                text=True,
                timeout=300 # 5 min timeout
            )
            
            if result.returncode == 0:
                return True, f"Success:\n{result.stdout}"
            else:
                return False, f"Failed (Code {result.returncode}):\n{result.stderr}\n{result.stdout}"
                
        except Exception as e:
            return False, str(e)
