# -*- coding: utf-8 -*-
import sys
import tempfile
import ssl
import os

# 1. 兼容性导入：处理 urllib2 (Py2) 和 urllib.request (Py3)
try:
    import urllib2 as request_module
except ImportError:
    import urllib.request as request_module

# 2. 兼容性编码处理 (仅在 Py2 下执行)
if sys.version_info[0] < 3:
    reload(sys)
    sys.setdefaultencoding('utf-8')

def run_remote_python():
    if len(sys.argv) < 2:
        return

    url = sys.argv[1]
    extra_args = sys.argv[2:]
    tmp_file_path = None
    
    try:
        # 3. 兼容性下载逻辑
        context = ssl._create_unverified_context()
        response = request_module.urlopen(url, context=context)
        content = response.read()

        # 4. 创建临时文件
        fd, tmp_file_path = tempfile.mkstemp(suffix=".py")
        
        # Py3 需要以二进制写入，或者指定 encoding
        if sys.version_info[0] >= 3:
            with os.fdopen(fd, 'wb') as tmp:
                tmp.write(content)
        else:
            with os.fdopen(fd, 'w') as tmp:
                tmp.write(content)

        # 5. 模拟环境：替换 sys.argv
        sys.argv = [url] + extra_args

        exec_globals = {
            "__name__": "__main__",
            "__file__": tmp_file_path,
            "__builtins__": __builtins__
        }
        
        # 兼容性执行逻辑
        if sys.version_info[0] < 3:
            # Python 2 方案
            execfile(tmp_file_path, exec_globals)
        else:
            # Python 3 方案
            with open(tmp_file_path, 'rb') as f:
                code = compile(f.read(), tmp_file_path, 'exec')
                exec(code, exec_globals)

    except Exception as e:
        sys.stderr.write("[Launcher Error] " + str(e) + "\n")
    finally:
        if tmp_file_path and os.path.exists(tmp_file_path):
            try:
                os.remove(tmp_file_path)
            except:
                pass

if __name__ == "__main__":
    run_remote_python()