# -*- mode: python ; coding: utf-8 -*-
"""PyInstaller specification for WebDrop Bridge.

This spec is shared by Windows and macOS build scripts.
It bundles runtime resources (webapp, icons, translations) and an optional
build-time .env file injected via WEBDROP_ENV_FILE.
"""

from pathlib import Path
import os


project_root = Path.cwd()

if not (project_root / "src").exists():
    env_root = os.environ.get("WEBDROP_PROJECT_ROOT")
    if env_root:
        candidate = Path(env_root).resolve()
        if (candidate / "src").exists():
            project_root = candidate

if not (project_root / "src").exists():
    # PyInstaller exposes SPECPATH while evaluating spec files.
    spec_path = globals().get("SPECPATH")
    if spec_path:
        spec_candidate = Path(spec_path).resolve()
        for candidate in (spec_candidate, spec_candidate.parent):
            if (candidate / "src").exists():
                project_root = candidate
                break

if not (project_root / "src").exists():
    raise SystemExit(
        "Unable to determine project root for PyInstaller spec. "
        "Run from repository root or set WEBDROP_PROJECT_ROOT."
    )

pathex = [str(project_root / "src")]
entry_script = str(project_root / "src" / "webdrop_bridge" / "main.py")

env_file = os.environ.get("WEBDROP_ENV_FILE")
bundle_id = os.environ.get("WEBDROP_BUNDLE_ID", "de.him_tools.webdrop-bridge")
bundle_version = os.environ.get("WEBDROP_VERSION", "0.0.0")

asset_prefix = os.environ.get("WEBDROP_ASSET_PREFIX")
exe_name = os.environ.get("WEBDROP_EXE_NAME", asset_prefix or "WebDropBridge")
app_name = asset_prefix or exe_name

icon_ico_default = project_root / "resources" / "icons" / "app.ico"
icon_icns_default = project_root / "resources" / "icons" / "app.icns"
icon_ico = Path(os.environ.get("WEBDROP_ICON_ICO", str(icon_ico_default)))
icon_icns = Path(os.environ.get("WEBDROP_ICON_ICNS", str(icon_icns_default)))

datas = [
    (str(project_root / "resources"), "resources"),
    (str(project_root / "webapp"), "webapp"),
]

ui_dir = project_root / "src" / "webdrop_bridge" / "ui"
for js_file in ui_dir.glob("*.js"):
    datas.append((str(js_file), "webdrop_bridge/ui"))

if env_file and Path(env_file).exists():
    datas.append((env_file, "."))

hiddenimports = [
    "PySide6.QtWebEngineCore",
    "PySide6.QtWebEngineWidgets",
    "PySide6.QtWebChannel",
]

a = Analysis(
    [entry_script],
    pathex=pathex,
    binaries=[],
    datas=datas,
    hiddenimports=hiddenimports,
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    noarchive=False,
    optimize=0,
)

pyz = PYZ(a.pure)

exe = EXE(
    pyz,
    a.scripts,
    [],
    exclude_binaries=True,
    name=exe_name,
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon=str(icon_ico) if icon_ico.exists() else None,
)

coll = COLLECT(
    exe,
    a.binaries,
    a.zipfiles,
    a.datas,
    strip=False,
    upx=True,
    upx_exclude=[],
    name=exe_name,
)

app = BUNDLE(
    coll,
    name=f"{app_name}.app",
    icon=str(icon_icns) if icon_icns.exists() else None,
    bundle_identifier=bundle_id,
    info_plist={
        "CFBundleName": app_name,
        "CFBundleDisplayName": app_name,
        "CFBundleShortVersionString": bundle_version,
        "CFBundleVersion": bundle_version,
    },
)