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

const requiredFiles = [
  "capacitor.config.ts",
  "dist/index.html",
  "dist/manifest.webmanifest",
  "dist/icons/icon-1024.png",
  "src/App.tsx",
  "src/services/cricut.ts",
  "ios/App/App/CraftLaunchFilesPlugin.swift",
  "ios/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme",
  "android/app/src/main/java/com/craftlaunch/studio/mobile/CraftLaunchFilesPlugin.java"
];

for (const file of requiredFiles) {
  if (!existsSync(join(process.cwd(), file))) {
    throw new Error(`Missing required mobile file: ${file}`);
  }
}

const packageJson = JSON.parse(readFileSync("package.json", "utf8"));
const capacitorConfig = readFileSync("capacitor.config.ts", "utf8");
const html = readFileSync("dist/index.html", "utf8");

if (packageJson.name !== "projectcraft-pro-mobile") {
  throw new Error("Mobile package name is not projectcraft-pro-mobile.");
}

if (!capacitorConfig.includes('appId: "com.craftlaunch.studio.mobile"')) {
  throw new Error("Capacitor appId must be com.craftlaunch.studio.mobile.");
}

if (!capacitorConfig.includes('appName: "ProjectCraft Pro"')) {
  throw new Error("Capacitor appName must be ProjectCraft Pro.");
}

if (!html.includes("viewport-fit=cover")) {
  throw new Error("Mobile viewport must include viewport-fit=cover for safe-area devices.");
}

if (packageJson.dependencies["@capacitor/filesystem"]) {
  throw new Error("Use the app-owned CraftLaunchFiles plugin instead of @capacitor/filesystem.");
}

const iosGeneratedConfigPath = "ios/App/App/capacitor.config.json";
if (existsSync(iosGeneratedConfigPath)) {
  const iosGeneratedConfig = JSON.parse(readFileSync(iosGeneratedConfigPath, "utf8"));
  const classList = iosGeneratedConfig.packageClassList ?? [];

  if (!classList.includes("CraftLaunchFilesPlugin")) {
    throw new Error("iOS generated config must register CraftLaunchFilesPlugin.");
  }

  if (classList.includes("FilesystemPlugin")) {
    throw new Error("iOS generated config must not register the removed FilesystemPlugin.");
  }
}

console.log("Mobile package validation passed.");
