#!/usr/bin/env python3
"""
Build script for Beyond-ET Godot project.

This script automates the process of exporting the Godot project for different platforms
using the command line interface.

Usage:
    python build.py [options]

Options:
    --type TYPE          Export type: release or debug (default: release)
    --preset NAME        Specific preset to build (if not specified, builds all presets)
    --skip-vrcft-module  Skip building the VRCFT module
"""

import os
import sys
import subprocess
import argparse
import json
import shutil
from pathlib import Path


def get_godot_path_from_settings():
    """Get the Godot path from .vscode/settings.json if available."""
    settings_path = os.path.join(".vscode", "settings.json")

    if not os.path.exists(settings_path):
        return None

    try:
        with open(settings_path, "r") as f:
            settings = json.load(f)
        godot_path = settings.get("godotTools.editorPath.godot4")
        if godot_path:
            return os.path.normpath(godot_path)
    except Exception as e:
        print(f"Error reading settings.json: {e}")
    return None


def get_all_presets():
    """Get all export presets from export_presets.cfg."""
    config_path = "export_presets.cfg"
    presets = []

    try:
        with open(config_path, "r") as f:
            content = f.read()

        preset_sections = content.split("[preset.")
        if preset_sections and not preset_sections[0].strip():
            preset_sections = preset_sections[1:]

        for section in preset_sections:
            for line in section.split("\n"):
                if line.strip().startswith("name="):
                    preset_name = line.split("=", 1)[1].strip('"')
                    presets.append(preset_name)
                    break
    except Exception as e:
        print(f"Error reading export_presets.cfg: {e}")
        sys.exit(1)

    return presets


def parse_arguments():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="Build script for Beyond-ET Godot project"
    )
    parser.add_argument(
        "--type",
        default="debug",
        choices=["release", "debug"],
        help="Export type: release or debug (default: release)",
    )
    parser.add_argument(
        "--preset",
        help="Specific preset to build (if not specified, builds all presets)",
    )
    parser.add_argument(
        "--skip-vrcft-module",
        action="store_true",
        help="Skip building the VRCFT module",
    )
    return parser.parse_args()


def toggle_openxr_setting(enable: bool):
    """Ensure OpenXR is enabled or disabled in project.godot based on the enable parameter."""
    project_godot_path = "project.godot"
    try:
        with open(project_godot_path, "r") as f:
            content = f.read()

        if enable:
            # Simply replace [xr] with [xr]\nopenxr/enabled=true
            if "[xr]" in content:
                content = content.replace("[xr]", "[xr]\nopenxr/enabled=true")
            else:
                # Add [xr] section if it doesn't exist
                content += "\n[xr]\nopenxr/enabled=true\n"
        else:
            # Remove openxr/enabled=true if it exists
            if "openxr/enabled=true" in content:
                content = content.replace("openxr/enabled=true\n", "")
                # If [xr] section is now empty, remove it

        with open(project_godot_path, "w") as f:
            f.write(content)
    except Exception as e:
        print(f"Error modifying project.godot: {e}")
        return False
    return True

# Modify project name (for window title difference with enrollment app)
def change_project_name(new_name):
    project_godot_path = "project.godot"
    lines = []
    with open(project_godot_path, 'r') as file:
        for line in file:
            if line.startswith('config/name='):
                lines.append(f'config/name="{new_name}"\n')
            else:
                lines.append(line)

    with open(project_godot_path, 'w') as file:
        file.writelines(lines)

def build_project(godot_path, preset_name, build_type):
    """Build the Godot project for a specific preset."""
    # Enable/disable OpenXR based on preset name
    is_xr_preset = "_XR" in preset_name
    if not toggle_openxr_setting(is_xr_preset):
        print(
            f"Failed to {'enable' if is_xr_preset else 'disable'} OpenXR for preset {preset_name}"
        )
        return False

    cmd = [godot_path]

    if build_type == "release":
        cmd.append("--export-release")
    else:
        cmd.append("--export-debug")

    # Set the app's title
    if is_xr_preset:
        change_project_name('Eyetracking Enrollment')
    else:
        change_project_name('Beyond Eyetracking')

    cmd.append(preset_name)
    print(f"Building preset: {preset_name}")

    try:
        result = subprocess.run(cmd, check=True, text=True, capture_output=True)
        if result.stderr:
            print(f"Warnings/Errors:\n{result.stderr}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"Build failed for preset {preset_name}")
        print(f"Error:\n{e.stderr}")
        return False


def build_dotnet_project():
    """Build the BeyondExtTrackingInterface .NET project."""
    project_path = ".BeyondExtTrackingInterface"
    print("Building BeyondExtTrackingInterface...")
    
    try:
        result = subprocess.run(
            ["dotnet", "build", project_path, "-c", "Release"],
            check=True,
            text=True,
            capture_output=True
        )
        if result.stderr:
            print(f"Warnings/Errors:\n{result.stderr}")
        return True
    except subprocess.CalledProcessError as e:
        print("Failed to build BeyondExtTrackingInterface")
        print(f"Error:\n{e.stderr}")
        return False


def copy_tracking_dll():
    """Copy the built DLL to VRCFaceTracking's CustomLibs directory."""
    # Get the AppData path
    appdata = os.getenv('APPDATA')
    if not appdata:
        print("Could not determine AppData directory")
        return False
    
    # Construct paths
    source_dll = os.path.join(".BeyondExtTrackingInterface", "bin", "Release", "net7.0", "BeyondExtTrackingInterface.dll")
    target_dir = os.path.join(appdata, "VRCFaceTracking", "CustomLibs")
    target_dll = os.path.join(target_dir, "BeyondExtTrackingInterface.dll")
    
    try:
        # Create target directory if it doesn't exist
        os.makedirs(target_dir, exist_ok=True)
        
        # Copy the DLL
        shutil.copy2(source_dll, target_dll)
        print(f"Successfully copied DLL to {target_dll}")
        return True
    except Exception as e:
        print(f"Failed to copy DLL: {e}")
        return False


def main():
    """Main function."""
    args = parse_arguments()
    godot_path = get_godot_path_from_settings() or "godot"

    if args.preset:
        presets = [args.preset]
    else:
        presets = get_all_presets()
        print(f"Building all presets: {', '.join(presets)}")

    success = True
    for preset in presets:
        if not build_project(godot_path, preset, args.type):
            success = False
    
    change_project_name('Beyond Eyetracking')

    # Build VRCFT module last if not skipped
    if not args.skip_vrcft_module:
        print("\nBuilding VRCFT module...")
        if not build_dotnet_project():
            print("Failed to build VRCFT module!")
            sys.exit(1)
        if not copy_tracking_dll():
            print("Failed to copy VRCFT module DLL!")
            sys.exit(1)
        print("Successfully built and deployed VRCFT module!")
    else:
        print("\nSkipping VRCFT module build as requested.")

    if success:
        print("All builds completed successfully!")

if __name__ == "__main__":
    main()
