// @ts-check

// Resolve sherpa-onnx native package paths for bundling into the packaged app.
// sherpa-onnx is an optionalDependency that pnpm hoists to the root .pnpm store,
// so electron-builder doesn't include it automatically. We find and bundle it via extraResources.
//
// This block is wrapped in try-catch because electron-vite also loads this config file
// (to read appId/productName) and converts require() calls to ESM imports that fail
// for Node built-ins. When that happens, we just return empty arrays (no sherpa bundling needed
// during the vite build step — only during electron-builder packaging).
let _sherpaResources = {};
try {
  const _path = require('path');
  const _fs = require('fs');

  /**
   * @param {string} platform
   * @param {string} arch
   * @returns {string | null}
   */
  function _findSherpaPackagePath(platform, arch) {
    const platformPackage = `sherpa-onnx-${platform}-${arch}`;

    // Check pnpm virtual store (monorepo root)
    const rootPnpmBase = _path.join(__dirname, '..', '..', 'node_modules', '.pnpm');
    if (_fs.existsSync(rootPnpmBase)) {
      try {
        const dirs = _fs.readdirSync(rootPnpmBase);
        const platformDir = dirs.find(d => d.startsWith(`${platformPackage}@`));
        if (platformDir) {
          const libPath = _path.join(rootPnpmBase, platformDir, 'node_modules', platformPackage);
          if (_fs.existsSync(libPath)) return libPath;
        }
      } catch { /* ignore */ }
    }

    // Check local pnpm store
    const localPnpmBase = _path.join(__dirname, 'node_modules', '.pnpm');
    if (_fs.existsSync(localPnpmBase)) {
      try {
        const dirs = _fs.readdirSync(localPnpmBase);
        const platformDir = dirs.find(d => d.startsWith(`${platformPackage}@`));
        if (platformDir) {
          const libPath = _path.join(localPnpmBase, platformDir, 'node_modules', platformPackage);
          if (_fs.existsSync(libPath)) return libPath;
        }
      } catch { /* ignore */ }
    }

    // Check standard node_modules
    const standardPath = _path.join(__dirname, 'node_modules', platformPackage);
    if (_fs.existsSync(standardPath)) return standardPath;

    const rootStandardPath = _path.join(__dirname, '..', '..', 'node_modules', platformPackage);
    if (_fs.existsSync(rootStandardPath)) return rootStandardPath;

    console.warn(`[electron-builder] Could not find ${platformPackage} - local TTS/STT may not work in packaged app`);
    return null;
  }

  /**
   * @param {string} platform
   * @param {string} arch
   * @returns {Array<{from: string, to: string, filter: string[]}>}
   */
  function _sherpaExtraResources(platform, arch) {
    const sherpaPath = _findSherpaPackagePath(platform, arch);
    if (!sherpaPath) return [];
    console.log(`[electron-builder] Bundling sherpa-onnx from: ${sherpaPath}`);
    return [{ from: sherpaPath, to: `sherpa-onnx-${platform}-${arch}`, filter: ['**/*'] }];
  }

  _sherpaResources = {
    macArm64: _sherpaExtraResources('darwin', 'arm64'),
    macX64: _sherpaExtraResources('darwin', 'x64'),
    winX64: _sherpaExtraResources('win', 'x64'),
    linuxX64: _sherpaExtraResources('linux', 'x64'),
    linuxArm64: _sherpaExtraResources('linux', 'arm64'),
  };
} catch {
  // Running inside electron-vite ESM context — sherpa bundling not needed here
  _sherpaResources = { macArm64: [], macX64: [], winX64: [], linuxX64: [], linuxArm64: [] };
}

/** @type {import('electron-builder').Configuration} */
module.exports = {
  appId: "app.dotagents",
  productName: "DotAgents",
  icon: "build/icon.png",
  directories: {
    buildResources: "build",
  },
  files: [
    "!**/.vscode/*",
    "!src/*",
    "!scripts/*",
    "!electron.vite.config.{js,ts,mjs,cjs}",
    "!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}",
    "!{.env,.env.*,.npmrc,pnpm-lock.yaml}",
    "!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}",
    "!*.{js,cjs,mjs,ts}",
    "!components.json",
    "!.prettierrc",
    "!dotagents-rs/*",
  ],
  asar: false,
  win: {
    icon: "build/icon.ico",
    executableName: "dotagents",
    target: [
      {
        target: "nsis",
        arch: ["x64"]
      }
    ],
    artifactName: "${productName}-${version}-${arch}.${ext}",
    requestedExecutionLevel: "asInvoker",
    sign: null,
    signAndEditExecutable: false,
    signDlls: false,
    extraResources: [
      {
        from: "resources/bin/dotagents-rs.exe",
        to: "bin/dotagents-rs.exe",
        filter: ["**/*"]
      },
      {
        from: "build/icon.ico",
        to: "icon.ico"
      },
      {
        from: "../../packages/mcp-whatsapp/dist",
        to: "mcp-whatsapp/dist",
        filter: ["**/*"]
      },
      {
        from: "resources/bundled-skills",
        to: "bundled-skills",
        filter: ["**/*"]
      },
      // sherpa-onnx native libraries are downloaded on demand at runtime
    ]
  },
  nsis: {
    artifactName: "${productName}-${version}-setup.${ext}",
    shortcutName: "${productName}",
    uninstallDisplayName: "${productName}",
    createDesktopShortcut: "always",
  },
  portable: {
    artifactName: "${productName}-${version}-${arch}-portable.${ext}",
  },
  mac: {
    binaries: [
      "resources/bin/dotagents-rs",
    ],
    extraResources: [
      {
        from: "../../packages/mcp-whatsapp/dist",
        to: "mcp-whatsapp/dist",
        filter: ["**/*"]
      },
      {
        from: "resources/bundled-skills",
        to: "bundled-skills",
        filter: ["**/*"]
      },
      // sherpa-onnx native libraries are downloaded on demand at runtime
    ],
    artifactName: "${productName}-${version}-${arch}.${ext}",
    entitlementsInherit: "build/entitlements.mac.plist",
    identity:
      process.env.CSC_IDENTITY_AUTO_DISCOVERY === "false"
        ? null
        : (process.env.CSC_NAME || "Apple Development"),
    // Disable hardened runtime and timestamp for development builds to avoid timestamp service errors
    // For production builds, set ENABLE_HARDENED_RUNTIME=true environment variable
    hardenedRuntime: process.env.ENABLE_HARDENED_RUNTIME === 'true',
    // All native extensions must be signed for notarization
    // Do NOT add signIgnore entries - Apple requires all binaries to be signed
    target: [
      {
        target: "dmg",
        arch: ["x64", "arm64"],
      },
      {
        target: "zip",
        arch: ["x64", "arm64"],
      },
      {
        target: "pkg",
        arch: ["x64", "arm64"],
      },
      // Temporarily disabled MAS build until installer certificate is available
      // {
      //   target: "mas",
      //   arch: ["arm64"]
      // }
    ],
    extendInfo: {
      NSCameraUsageDescription:
        "DotAgents may request camera access for enhanced AI features.",
      NSMicrophoneUsageDescription:
        "DotAgents requires microphone access for voice dictation and transcription.",
      NSDocumentsFolderUsageDescription:
        "DotAgents may access your Documents folder to save transcriptions and settings.",
      NSDownloadsFolderUsageDescription:
        "DotAgents may access your Downloads folder to save exported files.",
      LSMinimumSystemVersion: "12.0.0",
      CFBundleURLTypes: [
        {
          CFBundleURLName: "DotAgents Protocol",
          CFBundleURLSchemes: ["dotagents"],
        },
      ],
    },
    notarize:
      process.env.APPLE_API_KEY &&
      process.env.APPLE_API_KEY_ID &&
      process.env.APPLE_API_ISSUER
        ? true
        : process.env.APPLE_TEAM_ID &&
            process.env.APPLE_ID &&
            process.env.APPLE_APP_SPECIFIC_PASSWORD
          ? {
              teamId: process.env.APPLE_TEAM_ID,
            }
          : undefined,
  },
  mas: {
    artifactName: "${productName}-${version}-mas.${ext}",
    entitlementsInherit: "build/entitlements.mas.inherit.plist",
    entitlements: "build/entitlements.mas.plist",
    hardenedRuntime: false,
    identity: process.env.CSC_MAS_NAME || "3rd Party Mac Developer Application",
    provisioningProfile: process.env.MAS_PROVISIONING_PROFILE,
    category: "public.app-category.productivity",
    type: "distribution",
    preAutoEntitlements: false,
    cscInstallerLink: process.env.CSC_INSTALLER_LINK,
    extendInfo: {
      NSCameraUsageDescription:
        "DotAgents may request camera access for enhanced AI features.",
      NSMicrophoneUsageDescription:
        "DotAgents requires microphone access for voice dictation and transcription.",
      NSDocumentsFolderUsageDescription:
        "DotAgents may access your Documents folder to save transcriptions and settings.",
      NSDownloadsFolderUsageDescription:
        "DotAgents may access your Downloads folder to save exported files.",
      LSMinimumSystemVersion: "12.0.0",
      CFBundleURLTypes: [
        {
          CFBundleURLName: "DotAgents Protocol",
          CFBundleURLSchemes: ["dotagents"],
        },
      ],
    },
  },
  masDev: {
    artifactName: "${productName}-${version}-mas-dev.${ext}",
    entitlementsInherit: "build/entitlements.mas.inherit.plist",
    entitlements: "build/entitlements.mas.plist",
    hardenedRuntime: false,
    identity: process.env.CSC_MAS_DEV_NAME || "Mac Developer",
    provisioningProfile: process.env.MAS_DEV_PROVISIONING_PROFILE,
    category: "public.app-category.productivity",
    extendInfo: {
      NSCameraUsageDescription:
        "DotAgents may request camera access for enhanced AI features.",
      NSMicrophoneUsageDescription:
        "DotAgents requires microphone access for voice dictation and transcription.",
      NSDocumentsFolderUsageDescription:
        "DotAgents may access your Documents folder to save transcriptions and settings.",
      NSDownloadsFolderUsageDescription:
        "DotAgents may access your Downloads folder to save exported files.",
      LSMinimumSystemVersion: "10.15.0",
      CFBundleURLTypes: [
        {
          CFBundleURLName: "DotAgents Protocol",
          CFBundleURLSchemes: ["dotagents"],
        },
      ],
    },
  },
  dmg: {
    artifactName: "${productName}-${version}-${arch}.${ext}",
  },
  pkg: {
    artifactName: "${productName}-${version}-${arch}.${ext}",
    identity:
      process.env.CSC_INSTALLER_NAME ||
      process.env.CSC_NAME ||
      "Developer ID Application",
    allowAnywhere: false,
    allowCurrentUserHome: false,
    allowRootDirectory: false,
    isRelocatable: false,
    overwriteAction: "upgrade",
  },
  linux: {
    target: ["AppImage", "deb"],
    maintainer: "DotAgents <hi@techfren.net>",
    vendor: "DotAgents",
    category: "Utility",
    synopsis: "AI-powered agents with MCP integration",
    description: "DotAgents is an AI-powered agent tool with Model Context Protocol (MCP) integration for enhanced productivity.",
    desktop: {
      Name: "DotAgents",
      Comment: "AI-powered agents with MCP integration",
      GenericName: "AI Agent",
      Keywords: "ai;agent;assistant;mcp;automation;",
      Categories: "Utility;Development;",
      StartupWMClass: "dotagents",
      StartupNotify: false,
      Terminal: false,
      Type: "Application",
    },
    executableName: "dotagents",
    extraResources: [
      {
        from: "resources/bin/dotagents-rs",
        to: "bin/dotagents-rs",
        filter: ["**/*"]
      },
      {
        from: "../../packages/mcp-whatsapp/dist",
        to: "mcp-whatsapp/dist",
        filter: ["**/*"]
      },
      {
        from: "resources/bundled-skills",
        to: "bundled-skills",
        filter: ["**/*"]
      },
      // sherpa-onnx native libraries are downloaded on demand at runtime
    ]
  },
  deb: {
    artifactName: "${productName}_${version}_${arch}.${ext}",
    depends: [
      "libgtk-3-0",
      "libnotify4",
      "libnss3",
      "libxss1",
      "libxtst6",
      "xdg-utils",
      "libatspi2.0-0",
      "libuuid1",
      "libsecret-1-0"
    ],
    recommends: [
      "libappindicator3-1",
      "pulseaudio"
    ],
    afterInstall: "build/linux/postinst.sh",
    afterRemove: "build/linux/postrm.sh",
  },
  appImage: {
    artifactName: "${productName}-${version}-${arch}.${ext}",
  },
  npmRebuild: false,
  // After packing, clean up unnecessary files
  afterPack: async (context) => {
    const path = require('path');
    const fs = require('fs');

    // Find the app directory
    const appDir = path.join(context.appOutDir, 'resources', 'app');

    if (fs.existsSync(appDir)) {
      console.log('\n[AFTERPACK] Cleaning up unnecessary files...');
      console.log('[AFTERPACK] App directory:', appDir);

      try {
        // Remove lock files to reduce size
        const filesToRemove = ['bun.lock', 'pnpm-lock.yaml', 'package-lock.json'];
        for (const file of filesToRemove) {
          const filePath = path.join(appDir, file);
          if (fs.existsSync(filePath)) {
            console.log(`[AFTERPACK] Removing ${file}...`);
            fs.rmSync(filePath, { force: true });
          }
        }

        console.log('[AFTERPACK] Cleanup completed!\n');
      } catch (error) {
        console.error('[AFTERPACK] Cleanup failed:', error);
        // Don't throw - cleanup failures shouldn't block the build
      }
    }
  },
  publish: {
    provider: "github",
    owner: "aj47",
    repo: "dotagents-mono",
  },
  removePackageScripts: true,
}
