import flet as ft
import webbrowser
import json
import os
from pathlib import Path
import subprocess

class WebToAppConverter:
    def __init__(self):
        self.app_config = {
            "app_name": "MyWebApp",
            "app_id": "com.example.mywebapp",
            "version": "1.0.0",
            "start_url": "https://example.com",
            "width": 1200,
            "height": 800,
            "resizable": True,
            "fullscreen": False,
            "debug": False,
            "icon": None
        }
        
    def create_desktop_app(self, platform="windows"):
        """创建桌面应用程序"""
        template = f'''import webview

def main():
    window = webview.create_window(
        title="{self.app_config['app_name']}",
        url="{self.app_config['start_url']}",
        width={self.app_config['width']},
        height={self.app_config['height']},
        resizable={self.app_config['resizable']},
        fullscreen={self.app_config['fullscreen']}
    )
    webview.start(debug={self.app_config['debug']})

if __name__ == "__main__":
    main()
'''
        
        # 创建应用目录
        app_dir = Path(f"dist/{self.app_config['app_name']}")
        app_dir.mkdir(parents=True, exist_ok=True)
        
        # 保存主文件
        main_file = app_dir / "main.py"
        main_file.write_text(template)
        
        # 创建 requirements.txt
        requirements = app_dir / "requirements.txt"
        requirements.write_text("pywebview\n")
        
        # 创建配置文件
        config_file = app_dir / "app_config.json"
        with open(config_file, 'w') as f:
            json.dump(self.app_config, f, indent=4)
        
        # 创建启动脚本
        if platform == "windows":
            bat_file = app_dir / "start.bat"
            bat_file.write_text('''@echo off
echo 正在安装依赖...
python -m venv venv
call venv\\Scripts\\activate
pip install pywebview -i https://pypi.tuna.tsinghua.edu.cn/simple
echo.
echo 正在启动应用...
python main.py
pause''')
        else:
            sh_file = app_dir / "start.sh"
            sh_file.write_text('''#!/bin/bash
echo "正在安装依赖..."
python3 -m venv venv
source venv/bin/activate
pip install pywebview -i https://pypi.tuna.tsinghua.edu.cn/simple
echo ""
echo "正在启动应用..."
python3 main.py''')
            os.chmod(sh_file, 0o755)
        
        return str(app_dir)

    def create_pwa_manifest(self):
        """创建PWA清单文件"""
        manifest = {
            "name": self.app_config['app_name'],
            "short_name": self.app_config['app_name'],
            "description": f"{self.app_config['app_name']} - 打包的Web应用",
            "start_url": self.app_config['start_url'],
            "display": "standalone",
            "background_color": "#ffffff",
            "theme_color": "#2196F3",
            "icons": [
                {
                    "src": "icon-192.png",
                    "sizes": "192x192",
                    "type": "image/png"
                },
                {
                    "src": "icon-512.png",
                    "sizes": "512x512",
                    "type": "image/png"
                }
            ]
        }
        return json.dumps(manifest, indent=2)

    def create_service_worker(self):
        """创建Service Worker"""
        return '''self.addEventListener('install', event => {
    event.waitUntil(
        caches.open('app-cache').then(cache => {
            return cache.addAll([
                './',
                './index.html'
            ]);
        })
    );
});

self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request).then(response => {
            return response || fetch(event.request);
        })
    );
});
'''

def main(page: ft.Page):
    # 设置页面属性
    page.title = "网站打包工具 - Web to App Converter"
    page.theme_mode = ft.ThemeMode.LIGHT
    page.window_width = 1000
    page.window_height = 800
    page.window_resizable = True
    page.padding = 20
    page.scroll = "auto"
    
    converter = WebToAppConverter()
    
    # 状态变量
    current_config = converter.app_config.copy()
    
    # 输出区域
    output_text = ft.Text("", selectable=True, size=14)
    output_container = ft.Container(
        content=output_text,
        padding=10,
        bgcolor="#f0f0f0",
        border_radius=10,
        border=ft.border.all(1, "#cccccc"),
        expand=True,
        height=200
    )
    
    # 进度指示器
    progress_bar = ft.ProgressBar(visible=False, width=400)
    status_text = ft.Text("", color="blue")
    
    # 创建控件
    app_name_field = ft.TextField(
        label="应用名称",
        value=current_config["app_name"],
        width=300,
        hint_text="输入应用名称"
    )
    
    app_id_field = ft.TextField(
        label="应用ID (包名)",
        value=current_config["app_id"],
        width=300,
        hint_text="com.example.myapp"
    )
    
    url_field = ft.TextField(
        label="网站URL",
        value=current_config["start_url"],
        width=400,
        hint_text="https://example.com"
    )
    
    width_field = ft.TextField(
        label="窗口宽度",
        value=str(current_config["width"]),
        width=150,
        keyboard_type=ft.KeyboardType.NUMBER
    )
    
    height_field = ft.TextField(
        label="窗口高度",
        value=str(current_config["height"]),
        width=150,
        keyboard_type=ft.KeyboardType.NUMBER
    )
    
    resizable_switch = ft.Switch(
        label="允许调整窗口大小",
        value=current_config["resizable"]
    )
    
    fullscreen_switch = ft.Switch(
        label="全屏模式",
        value=current_config["fullscreen"]
    )
    
    debug_switch = ft.Switch(
        label="调试模式",
        value=current_config["debug"]
    )
    
    version_field = ft.TextField(
        label="版本号",
        value=current_config["version"],
        width=150
    )
    
    # 平台选择 - 使用Checkbox替代RadioGroup
    platform_container = ft.Column([
        ft.Text("目标平台:", weight=ft.FontWeight.BOLD),
        ft.Row([
            ft.Checkbox(label="Windows", value=True),
            ft.Checkbox(label="Linux/macOS"),
            ft.Checkbox(label="PWA (渐进式Web应用)")
        ])
    ])
    
    def update_config(e=None):
        """更新配置"""
        try:
            current_config.update({
                "app_name": app_name_field.value or "MyWebApp",
                "app_id": app_id_field.value or "com.example.mywebapp",
                "start_url": url_field.value or "https://example.com",
                "width": int(width_field.value) if width_field.value else 1200,
                "height": int(height_field.value) if height_field.value else 800,
                "resizable": resizable_switch.value,
                "fullscreen": fullscreen_switch.value,
                "debug": debug_switch.value,
                "version": version_field.value or "1.0.0"
            })
            converter.app_config = current_config
            status_text.value = "✅ 配置已更新"
            page.update()
        except Exception as ex:
            status_text.value = f"❌ 配置更新失败: {str(ex)}"
            page.update()
    
    def open_output_folder(e):
        """打开输出文件夹"""
        output_path = Path("dist")
        if output_path.exists():
            try:
                if os.name == 'nt':  # Windows
                    os.startfile(str(output_path))
                elif sys.platform == 'darwin':  # macOS
                    subprocess.run(['open', str(output_path)])
                else:  # Linux
                    subprocess.run(['xdg-open', str(output_path)])
                output_text.value = f"📁 已打开输出文件夹: {output_path}"
            except Exception as ex:
                output_text.value = f"❌ 无法打开文件夹: {str(ex)}"
        else:
            output_text.value = "❌ 输出文件夹不存在，请先创建应用"
        page.update()
    
    def test_website(e):
        """测试网站"""
        try:
            url = url_field.value
            if not url:
                output_text.value = "❌ 请输入网站URL"
                return
                
            if not url.startswith(('http://', 'https://')):
                url = 'https://' + url
                
            webbrowser.open(url)
            output_text.value = f"🌐 正在打开网站: {url}"
        except Exception as ex:
            output_text.value = f"❌ 无法打开网站: {str(ex)}"
        page.update()
    
    def create_app(e):
        """创建应用程序"""
        try:
            update_config()
            progress_bar.visible = True
            status_text.value = "🔄 正在创建应用..."
            page.update()
            
            # 获取选中的平台
            platforms = []
            if platform_container.controls[1].controls[0].value:  # Windows
                platforms.append("windows")
            if platform_container.controls[1].controls[1].value:  # Linux
                platforms.append("linux")
            if platform_container.controls[1].controls[2].value:  # PWA
                platforms.append("pwa")
            
            if not platforms:
                output_text.value = "❌ 请至少选择一个目标平台"
                progress_bar.visible = False
                status_text.value = ""
                page.update()
                return
            
            output_text.value = f"🔄 正在为 {', '.join(platforms)} 平台创建应用...\n"
            
            # 创建桌面应用
            if "windows" in platforms or "linux" in platforms:
                for platform in ["windows", "linux"]:
                    if platform in platforms:
                        output_path = converter.create_desktop_app(platform)
                        output_text.value += f"\n✅ {platform.upper()} 应用已创建到: {output_path}\n"
            
            # 创建PWA应用
            if "pwa" in platforms:
                pwa_dir = Path(f"dist/{current_config['app_name']}_PWA")
                pwa_dir.mkdir(parents=True, exist_ok=True)
                
                # 创建manifest
                manifest = converter.create_pwa_manifest()
                (pwa_dir / "manifest.json").write_text(manifest)
                
                # 创建service worker
                sw = converter.create_service_worker()
                (pwa_dir / "sw.js").write_text(sw)
                
                # 创建HTML文件
                html_content = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{current_config['app_name']}</title>
    <link rel="manifest" href="manifest.json">
    <style>
        body, html {{
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }}
        iframe {{
            width: 100%;
            height: 100%;
            border: none;
        }}
    </style>
</head>
<body>
    <iframe src="{current_config['start_url']}"></iframe>
    
    <script>
        if ('serviceWorker' in navigator) {{
            navigator.serviceWorker.register('sw.js');
        }}
    </script>
</body>
</html>'''
                
                (pwa_dir / "index.html").write_text(html_content)
                output_text.value += f"\n✅ PWA 应用已创建到: {pwa_dir}\n"
            
            output_text.value += f"\n🎉 应用创建完成！\n"
            output_text.value += f"📱 应用名称: {current_config['app_name']}\n"
            output_text.value += f"📦 版本: {current_config['version']}\n"
            output_text.value += f"🌐 目标URL: {current_config['start_url']}\n"
            
            # 显示下一步操作提示
            output_text.value += "\n📋 下一步操作：\n"
            if "windows" in platforms or "linux" in platforms:
                output_text.value += "1. 进入dist目录下的应用文件夹\n"
                output_text.value += "2. 运行start.bat(Windows)或start.sh(Linux/macOS)\n"
            
            progress_bar.visible = False
            status_text.value = "✅ 应用创建完成"
            
        except Exception as ex:
            output_text.value = f"❌ 创建应用时出错: {str(ex)}"
            progress_bar.visible = False
            status_text.value = "❌ 创建失败"
        
        page.update()
    
    def reset_form(e):
        """重置表单"""
        app_name_field.value = "MyWebApp"
        app_id_field.value = "com.example.mywebapp"
        url_field.value = "https://example.com"
        width_field.value = "1200"
        height_field.value = "800"
        resizable_switch.value = True
        fullscreen_switch.value = False
        debug_switch.value = False
        version_field.value = "1.0.0"
        
        # 重置平台选择
        for i, checkbox in enumerate(platform_container.controls[1].controls):
            checkbox.value = (i == 0)  # 只选中第一个
        
        output_text.value = ""
        status_text.value = ""
        update_config()
        page.update()
    
    def save_config(e):
        """保存配置"""
        update_config()
        config_path = Path("webapp_config.json")
        with open(config_path, 'w') as f:
            json.dump(current_config, f, indent=4)
        output_text.value = f"💾 配置已保存到: {config_path.absolute()}"
        page.update()
    
    def load_config(e):
        """加载配置"""
        config_path = Path("webapp_config.json")
        if config_path.exists():
            try:
                with open(config_path, 'r') as f:
                    loaded_config = json.load(f)
                    app_name_field.value = loaded_config.get("app_name", "MyWebApp")
                    app_id_field.value = loaded_config.get("app_id", "com.example.mywebapp")
                    url_field.value = loaded_config.get("start_url", "https://example.com")
                    width_field.value = str(loaded_config.get("width", 1200))
                    height_field.value = str(loaded_config.get("height", 800))
                    resizable_switch.value = loaded_config.get("resizable", True)
                    fullscreen_switch.value = loaded_config.get("fullscreen", False)
                    debug_switch.value = loaded_config.get("debug", False)
                    version_field.value = loaded_config.get("version", "1.0.0")
                update_config()
                output_text.value = f"📂 配置已从 {config_path} 加载"
            except Exception as ex:
                output_text.value = f"❌ 加载配置失败: {str(ex)}"
        else:
            output_text.value = "⚠️ 未找到保存的配置"
        page.update()
    
    def show_help(e):
        """显示帮助信息"""
        help_text = """🎯 网站打包工具使用说明

📌 功能概述：
1. 将任何网站打包为桌面应用
2. 生成PWA（渐进式Web应用）
3. 支持多平台（Windows/Linux/macOS）
4. 可自定义窗口大小和功能

📌 使用方法：
1. 填写基本信息（应用名称、URL等）
2. 配置窗口设置
3. 选择目标平台
4. 点击"创建应用"

📌 平台说明：
• Windows: 生成.bat启动脚本
• Linux/macOS: 生成.sh启动脚本
• PWA: 生成Web应用，可添加到手机桌面

📌 注意事项：
1. 某些网站可能限制iframe嵌入
2. PWA需要HTTPS环境
3. 首次运行会安装依赖，请保持网络连接
"""
        output_text.value = help_text
        page.update()
    
    # 创建UI布局
    page.add(
        ft.Column([
            # 标题
            ft.Row([
                ft.Text("🌐 网站打包工具", size=28, weight=ft.FontWeight.BOLD),
            ], alignment=ft.MainAxisAlignment.CENTER),
            
            ft.Divider(height=20),
            
            # 基本设置
            ft.Text("基本设置", size=18, weight=ft.FontWeight.BOLD),
            ft.Row([app_name_field, app_id_field]),
            ft.Row([
                url_field, 
                ft.IconButton(
                    icon="open_in_browser", 
                    on_click=test_website,
                    tooltip="测试网站"
                )
            ]),
            ft.Row([version_field]),
            
            ft.Divider(height=20),
            
            # 窗口设置
            ft.Text("窗口设置", size=18, weight=ft.FontWeight.BOLD),
            ft.Row([width_field, height_field]),
            ft.Column([
                resizable_switch,
                fullscreen_switch,
                debug_switch
            ]),
            
            ft.Divider(height=20),
            
            # 平台选择
            platform_container,
            
            ft.Divider(height=20),
            
            # 按钮区域
            ft.Row([
                ft.ElevatedButton(
                    "📱 创建应用",
                    icon="build",
                    on_click=create_app,
                    style=ft.ButtonStyle(
                        color="white",
                        bgcolor="blue"
                    )
                ),
                ft.ElevatedButton(
                    "💾 保存配置",
                    icon="save",
                    on_click=save_config
                ),
                ft.ElevatedButton(
                    "📂 加载配置",
                    icon="upload_file",
                    on_click=load_config
                ),
                ft.ElevatedButton(
                    "🔄 重置表单",
                    icon="restart_alt",
                    on_click=reset_form
                ),
                ft.ElevatedButton(
                    "📁 打开输出文件夹",
                    icon="folder_open",
                    on_click=open_output_folder
                )
            ], alignment=ft.MainAxisAlignment.CENTER),
            
            ft.Row([
                progress_bar,
                status_text
            ], alignment=ft.MainAxisAlignment.CENTER),
            
            # 输出区域
            ft.Text("输出信息", size=18, weight=ft.FontWeight.BOLD),
            output_container,
            
            # 帮助提示
            ft.Text(
                "💡 提示: 创建的应用将保存在 dist 文件夹中。对于PWA，需要HTTPS才能安装。",
                size=12,
                color="gray",
                italic=True
            )
        ], scroll="auto", spacing=10)
    )

if __name__ == "__main__":
    # 确保dist目录存在
    Path("dist").mkdir(exist_ok=True)
    
    print("=" * 50)
    print("网站打包工具 v1.0")
    print("=" * 50)
    print("正在启动应用...")
    
    # 运行应用 - 使用最新版本的启动方式
    ft.app(target=main)