import os
import sys
import zipfile
import shutil

# Import build variables
sys.path.insert(0, os.getcwd())
import buildVars

# Environment
env = Environment()

# Get addon info
addon_info = buildVars.addon_info
addon_name = addon_info["addon_name"]
addon_version = addon_info["addon_version"]

# Output file name
addon_file = f"{addon_name}-{addon_version}.nvda-addon"

def create_manifest(target, source, env):
    """Create manifest.ini from template"""
    template_path = "manifest.ini.tpl"
    manifest_path = os.path.join("addon", "manifest.ini")

    with open(template_path, "r", encoding="utf-8") as f:
        content = f.read()

    # Replace placeholders
    for key, value in addon_info.items():
        placeholder = "{" + key + "}"
        # Skip updateChannel if None
        if key == "addon_updateChannel" and value is None:
            # Remove the entire line
            import re
            content = re.sub(r'^updateChannel = .*\n?', '', content, flags=re.MULTILINE)
        else:
            content = content.replace(placeholder, str(value) if value is not None else "")

    with open(manifest_path, "w", encoding="utf-8") as f:
        f.write(content)

    return None

def create_addon(target, source, env):
    """Create the .nvda-addon file (zip archive)"""
    addon_dir = "addon"
    output_file = str(target[0])

    # Remove old addon file if it exists
    if os.path.exists(output_file):
        os.remove(output_file)

    # Create zip file
    with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zf:
        for root, dirs, files in os.walk(addon_dir):
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.relpath(file_path, addon_dir)
                zf.write(file_path, arcname)

    print(f"Created {output_file}")
    return None

# Build targets
manifest = env.Command(
    os.path.join("addon", "manifest.ini"),
    "manifest.ini.tpl",
    create_manifest
)

addon = env.Command(
    addon_file,
    [manifest, "addon"],
    create_addon
)

# Set dependencies
env.Depends(addon, manifest)

# Default target
env.Default(addon)

# Clean target - remove generated files
if env.GetOption('clean'):
    manifest_path = os.path.join("addon", "manifest.ini")
    if os.path.exists(manifest_path):
        os.remove(manifest_path)
        print(f"Removed {manifest_path}")
    if os.path.exists(addon_file):
        os.remove(addon_file)
        print(f"Removed {addon_file}")
