#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
import subprocess
import sys
from pathlib import Path

def setup_windows_build():
    """Setup Windows build environment"""
    print("=== Setting up Windows build environment ===")
    
    # Ensure we're in the gui directory
    work_dir = Path(__file__).parent
    os.chdir(work_dir)

    # Check required files
    required_files = [
        "k230_arduino_flash.spec",
        "k230_arduino_flash.py",
    ]

    for file in required_files:
        if not Path(file).exists():
            print(f"Error: Missing required file {file}")
            return False

    print("Windows build environment check completed")
    return True

def build_executable():
    """Build exe file using PyInstaller"""
    print("=== Building Windows executable ===")
    
    try:
        # Clean previous builds
        if Path("build").exists():
            shutil.rmtree("build")
        if Path("dist").exists():
            shutil.rmtree("dist")
        
        # Run PyInstaller
        cmd = [
            sys.executable, "-m", "PyInstaller",
            "--clean", "-y",
            "k230_arduino_flash.spec"
        ]

        print(f"Executing command: {' '.join(cmd)}")
        result = subprocess.run(cmd, capture_output=True, text=True)

        if result.returncode != 0:
            print(f"PyInstaller build failed:")
            print(f"STDOUT: {result.stdout}")
            print(f"STDERR: {result.stderr}")
            return False
        
        print("PyInstaller build successful")
        return True
        
    except Exception as e:
        print(f"Error occurred during build: {e}")
        return False

def update_files():
    work_dir = Path(__file__).parent

    release_dir = Path(work_dir) / "windows"
    shutil.rmtree(release_dir, ignore_errors=True)

    dist_dir = Path(work_dir) / "dist" / "k230_arduino_flash"
    if not dist_dir.exists():
        print(f"dist_dir {dist_dir} not exists")
        return False

    shutil.copytree(dist_dir, release_dir)

    shutil.rmtree(Path(work_dir)/"build")
    shutil.rmtree(Path(work_dir)/"dist")

    return True

def main():
    """Main function"""
    print("K230 Arduino Flash - Windows Build Script")
    print("=" * 50)
    
    if not setup_windows_build():
        sys.exit(1)
    
    if not build_executable():
        sys.exit(1)

    if not update_files():
        sys.exit(1)

    print("\n=== Windows build completed ===")
    print("Output directory: dist/k230_arduino_flash/")

if __name__ == "__main__":
    main()
