#!/usr/bin/env node

import { existsSync, readFileSync, readdirSync } from "node:fs"
import { join, resolve } from "node:path"

const repoRoot = resolve(import.meta.dirname, "..", "..")
const installerDir = join(repoRoot, "dist", "installer")

let failures = 0

function check(label, condition, detail) {
  if (condition) {
    console.log(`  PASS: ${label}`)
  } else {
    console.error(`  FAIL: ${label}${detail ? ` — ${detail}` : ""}`)
    failures++
  }
}

function findAppDir(dir) {
  if (!existsSync(dir)) return null
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
    if (entry.isDirectory() && entry.name.endsWith(".app")) {
      return join(dir, entry.name)
    }
  }
  return null
}

console.log("mac-package-smoke: validating electron-builder output")

// 1. Check for .app directory
const macArm64Dir = join(installerDir, "mac-arm64")
const appDir = findAppDir(macArm64Dir) || findAppDir(installerDir)
check(".app directory exists", Boolean(appDir), `searched in: ${macArm64Dir} and ${installerDir}`)

if (appDir) {
  // 2. Check for vendor/openclaw-runtime in Resources
  const resourcesDir = join(appDir, "Contents", "Resources")
  const runtimeDir = join(resourcesDir, "vendor", "openclaw-runtime")
  check("vendor/openclaw-runtime in app Resources", existsSync(runtimeDir), `not found: ${runtimeDir}`)

  if (existsSync(runtimeDir)) {
    const manifestPath = join(runtimeDir, "runtime-manifest.json")
    check("runtime-manifest.json in Resources", existsSync(manifestPath))
    check("node/bin/node in Resources", existsSync(join(runtimeDir, "node", "bin", "node")))
    check("python/bin/python3 in Resources", existsSync(join(runtimeDir, "python", "bin", "python3")))
    if (existsSync(manifestPath)) {
      try {
        const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))
        check("packaged manifest platform is darwin", manifest.platform === "darwin", `got: ${manifest.platform}`)
        check("packaged manifest arch is arm64", manifest.arch === "arm64", `got: ${manifest.arch}`)
      } catch (e) {
        check("packaged runtime-manifest.json is valid JSON", false, e.message)
      }
    }
  }

  // 3. Check for app.asar
  const asarPath = join(resourcesDir, "app.asar")
  check("app.asar exists", existsSync(asarPath), `not found: ${asarPath}`)

  // 4. Check Info.plist
  const plistPath = join(appDir, "Contents", "Info.plist")
  check("Info.plist exists", existsSync(plistPath))
}

// 5. Check for DMG file (optional, --dir mode doesn't produce one)
const dmgFiles = existsSync(installerDir)
  ? readdirSync(installerDir, { withFileTypes: true })
    .filter(e => e.isFile() && e.name.endsWith(".dmg"))
    .map(e => e.name)
  : []
if (dmgFiles.length > 0) {
  console.log(`  INFO: Found DMG file(s): ${dmgFiles.join(", ")}`)
}

// Summary
console.log("")
if (failures === 0) {
  console.log("mac-package-smoke: ALL PASSED")
} else {
  console.error(`mac-package-smoke: ${failures} FAILURE(S)`)
  process.exit(1)
}
