#!/usr/bin/env python3
"""Gedragstest met echte Sparkle, zonder de volledige app te bouwen."""
import pathlib
import plistlib
import subprocess
import tempfile
import uuid

ROOT = pathlib.Path(__file__).resolve().parents[1]
FRAMEWORKS = ROOT / '.local-build/SourcePackages/artifacts/sparkle/Sparkle/Sparkle.xcframework/macos-arm64_x86_64'
source = (ROOT / 'VoiceInk/VoiceInk.swift').read_text()
# 2026-09-07: compileer de productieklasse los om zware transcriptie-afhankelijkheden te vermijden.
updater = source.split('class UpdaterViewModel: ObservableObject {', 1)[1].split('\nstruct CheckForUpdatesView:', 1)[0]
swift = '''import AppKit
import SwiftUI
import Combine
import Sparkle
class UpdaterViewModel: ObservableObject {''' + updater + '''
let application = NSApplication.shared
let defaults = UserDefaults.standard
let domain = Bundle.main.bundleIdentifier!
defer { defaults.removePersistentDomain(forName: domain) }
defaults.set(false, forKey: "autoUpdateCheck")
defaults.set(Date(), forKey: "SULastCheckTime")
let model = UpdaterViewModel()
var failures = [String]()
func check(_ condition: Bool, _ message: String) {
    if !condition { failures.append(message) }
}
check(model.canCheckForUpdates, "Na starten moet de gebruiker updates kunnen controleren")
check(!defaults.bool(forKey: "SUEnableAutomaticChecks"), "Bestaande uitgeschakelde voorkeur moet behouden blijven")
model.toggleAutoUpdates(true)
check(defaults.bool(forKey: "autoUpdateCheck"), "Inschakelen moet de zichtbare instelling bewaren")
check(defaults.bool(forKey: "SUEnableAutomaticChecks"), "Inschakelen moet echte Sparkle-controles activeren")
model.toggleAutoUpdates(false)
check(!defaults.bool(forKey: "autoUpdateCheck"), "Uitschakelen moet de zichtbare instelling bewaren")
check(!defaults.bool(forKey: "SUEnableAutomaticChecks"), "Uitschakelen moet echte Sparkle-controles stoppen")
model.silentlyCheckForUpdates()
check(model.canCheckForUpdates, "Een uitgeschakelde stille controle mag de updateknop niet blokkeren")
if !failures.isEmpty {
    for failure in failures { print("FAIL: " + failure) }
    exit(1)
}
print("PASS: Sparkle gestart; controle beschikbaar; automatisch controleren volgt aan/uit-voorkeur")
'''
with tempfile.TemporaryDirectory(prefix='proat-sparkle-test-') as temporary:
    temp = pathlib.Path(temporary)
    bundle = temp / 'UpdaterTest.app/Contents'
    (bundle / 'MacOS').mkdir(parents=True)
    info = plistlib.loads((ROOT / 'VoiceInk/Info.plist').read_bytes())
    info.update(CFBundleIdentifier='ai.vakwark.proat.updater-test.' + uuid.uuid4().hex,
                CFBundleExecutable='UpdaterTest', CFBundleName='UpdaterTest',
                CFBundleVersion='1', CFBundleShortVersionString='1.0', CFBundlePackageType='APPL')
    (bundle / 'Info.plist').write_bytes(plistlib.dumps(info))
    (temp / 'main.swift').write_text(swift)
    executable = bundle / 'MacOS/UpdaterTest'
    subprocess.run(['swiftc', str(temp / 'main.swift'), '-F', str(FRAMEWORKS), '-framework', 'Sparkle',
                    '-Xlinker', '-rpath', '-Xlinker', str(FRAMEWORKS), '-o', str(executable)], check=True)
    subprocess.run([str(executable)], check=True)
