#!/usr/bin/env python3
"""
Automation Script Wrapper
Provides a unified interface for executing automation scripts with proper error handling
and result reporting back to the Node.js backend.
"""

import sys
import json
import traceback
import os
from pathlib import Path

def main():
    try:
        if len(sys.argv) < 3:
            print(json.dumps({
                "success": False,
                "error": "Usage: script_wrapper.py <script_name> <file_path> [output_dir] [job_id] [api_base_url] [user_id] [credits_used]"
            }), file=sys.stderr)
            sys.exit(1)

        script_name = sys.argv[1]
        file_path = sys.argv[2]
        
        # Optional parameters for CTG port tracking and other refactored scripts
        output_dir = sys.argv[3] if len(sys.argv) > 3 else 'results'
        job_id = sys.argv[4] if len(sys.argv) > 4 else None
        api_base_url = sys.argv[5] if len(sys.argv) > 5 else None
        user_id = sys.argv[6] if len(sys.argv) > 6 else None
        credits_used = sys.argv[7] if len(sys.argv) > 7 else None

        if not os.path.exists(file_path):
            print(json.dumps({
                "success": False,
                "error": f"File not found: {file_path}"
            }), file=sys.stderr)
            sys.exit(1)

        automation = None
        success = False
        results = []

        if script_name == 'damco_tracking_maersk':
            # Use the refactored class with server communication support
            from damco_tracking_maersk import DamcoTrackingAutomation, ServerClient
            
            # Create server client if parameters provided
            server_client = None
            if api_base_url and user_id:
                server_client = ServerClient(api_base_url, user_id, job_id or 'wrapper_job')
            
            # Instantiate automation with server client
            automation = DamcoTrackingAutomation(
                headless=True,
                output_dir=output_dir,
                job_id=job_id or 'wrapper_job',
                server_client=server_client
            )
            
            # Store input file path and credits for server uploads
            automation.input_file_path = file_path
            automation.credits_used = float(credits_used) if credits_used else 0.0
            
            # Run automation (this will handle server uploads automatically)
            success = automation.run(file_path)
            results = getattr(automation, 'results', [])

        elif script_name == 'ctg_port_tracking':
            # Use the refactored class with server communication support
            from ctg_port_tracking import CtgPortTrackingAutomation, ServerClient
            
            # Create server client if parameters provided
            server_client = None
            if api_base_url and user_id:
                server_client = ServerClient(api_base_url, user_id, job_id or 'wrapper_job')
            
            # Instantiate automation with server client
            automation = CtgPortTrackingAutomation(
                headless=True,
                output_dir=output_dir,
                job_id=job_id or 'wrapper_job',
                server_client=server_client
            )
            
            # Store input file path and credits for server uploads
            automation.input_file_path = file_path
            automation.credits_used = float(credits_used) if credits_used else 0.0
            
            # Run automation (this will handle server uploads automatically)
            success = automation.run(file_path)
            results = getattr(automation, 'results', [])

        elif script_name == 'egm_download':
            # EGM download uses main() function directly, but we need to set up sys.argv
            # Save original argv and replace with expected arguments
            import sys as sys_module
            original_argv = sys_module.argv[:]
            try:
                # Build arguments for egm_download.main()
                egm_args = [file_path, output_dir, job_id or 'wrapper_job']
                if api_base_url and user_id:
                    egm_args.extend([api_base_url, user_id])
                    if credits_used:
                        egm_args.append(credits_used)
                
                # Replace sys.argv temporarily to call main()
                sys_module.argv = ['egm_download.py'] + egm_args
                
                # Import and call main() which will handle execution
                from egm_download import main as egm_main
                exit_code = egm_main()
                success = (exit_code == 0)
                results = []
            finally:
                # Restore original argv
                sys_module.argv = original_argv

        elif script_name == 'example_automation':
            from example_automation import ExampleAutomation
            automation = ExampleAutomation()
            success = automation.run_automation(file_path)
            results = getattr(automation, 'results', [])

        else:
            print(json.dumps({
                "success": False,
                "error": f"Unknown script: {script_name}"
            }), file=sys.stderr)
            sys.exit(1)

        result = {
            "success": success,
            "results": results,
            "message": "Automation completed successfully" if success else "Automation failed",
            "script": script_name,
            "file": file_path
        }

        print(json.dumps(result))
        sys.exit(0 if success else 1)

    except ImportError as e:
        error_result = {
            "success": False,
            "error": f"Failed to import automation module: {str(e)}",
            "traceback": traceback.format_exc()
        }
        print(json.dumps(error_result), file=sys.stderr)
        sys.exit(1)

    except Exception as e:
        error_result = {
            "success": False,
            "error": str(e),
            "traceback": traceback.format_exc()
        }
        print(json.dumps(error_result), file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()