#!/usr/bin/env python3
"""创建临时远程访问链接"""

import subprocess
import sys
import json

def create_cloudflare_tunnel(port):
    """使用 cloudflared 创建临时隧道（仅支持 HTTP/HTTPS）"""
    try:
        # 检查认证
        result = subprocess.run(
            ['cloudflared', 'tunnel', 'list'],
            capture_output=True,
            text=True
        )
        
        if result.returncode != 0 and 'authentication' in result.stderr.lower():
            print("❌ 需要先登录 Cloudflare:")
            print("   cloudflared tunnel login")
            return None
        
        # 创建临时隧道
        cmd = ['cloudflared', 'tunnel', '--url', f'http://localhost:{port}']
        print(f"🚀 启动临时隧道: http://localhost:{port}")
        print("   等待 URL...")
        
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        
        # 读取输出获取 URL
        import time
        for line in process.stdout:
            if 'trycloudflare.com' in line:
                url = line.strip()
                print(f"\n✅ 隧道已创建!")
                print(f"   {url}")
                print(f"\n   有效期: 约 24 小时")
                return url
            if 'Error' in line or 'error' in line:
                print(f"❌ 错误: {line}")
                return None
        
        return None
        
    except Exception as e:
        print(f"❌ 创建隧道失败: {e}")
        return None

if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8899
    create_cloudflare_tunnel(port)
