import { predictAiBehaviorLibraries } from "@specverse/engines/ai";
const AI_LIBRARY_VERSIONS = {
  "jsonwebtoken": { runtime: "^9.0.0", types: "^9.0.0" },
  "bcryptjs": { runtime: "^2.4.3", types: "^2.4.0" },
  "uuid": { runtime: "^9.0.0", types: "^9.0.0" },
  "crypto": {
    runtime: "*"
    /* Node built-in */
  },
  "expr-eval": { runtime: "^2.0.2" }
};
function resolveOrmName(manifest) {
  if (!manifest) return "PrismaORM";
  const inner = manifest.manifests ? Object.values(manifest.manifests)[0] : manifest;
  if (!inner) return "PrismaORM";
  const caps = Array.isArray(inner.capabilityMappings) ? inner.capabilityMappings : [];
  const ormCap = caps.find((m) => m?.capability === "orm.client") || caps.find((m) => m?.capability === "orm.schema");
  if (ormCap) return ormCap.implementation || ormCap.instanceFactory || "PrismaORM";
  return inner.defaultMappings?.orm || "PrismaORM";
}
function generateBackendPackageJson(context) {
  const { spec, manifest } = context;
  const appName = (spec.metadata?.component || "app").toLowerCase().replace(/\s+/g, "-");
  const orm = resolveOrmName(manifest);
  const isMongoNative = orm === "MongoDBNativeDriver";
  const isPgNative = orm === "PostgresNativeDriver";
  const dbScripts = isMongoNative ? {} : isPgNative ? {
    "db:setup": 'psql "$POSTGRES_URL" -f src/db/schema.sql'
  } : {
    "db:setup": "prisma generate && prisma db push",
    "db:generate": "prisma generate",
    "db:push": "prisma db push",
    "db:migrate": "prisma migrate dev",
    "db:studio": "prisma studio",
    "db:seed": "tsx prisma/seed.ts"
  };
  const ormDeps = isMongoNative ? { "mongodb": "^6.3.0" } : isPgNative ? { "pg": "^8.11.0" } : { "@prisma/client": "^5.7.0" };
  const ormDevDeps = isMongoNative ? {} : isPgNative ? { "@types/pg": "^8.11.0" } : { "prisma": "^5.7.0" };
  const pkg = {
    name: `${appName}-backend`,
    version: spec.metadata?.version || "1.0.0",
    description: `Backend API for ${spec.metadata?.component || "application"}`,
    type: "module",
    bin: {
      [appName]: "./bin/cli.mjs"
    },
    scripts: {
      // Development
      "dev": "tsx watch src/main.ts",
      "dev:debug": "tsx watch --inspect src/main.ts",
      // Build
      "build": "tsc",
      "build:watch": "tsc --watch",
      // Production
      "start": "node dist/main.js",
      // Database (ORM-specific; empty for native driver)
      ...dbScripts,
      // Testing
      "test": "vitest run --passWithNoTests",
      "test:watch": "vitest watch",
      "test:coverage": "vitest --coverage",
      // Linting
      "lint": "eslint src --ext .ts",
      "lint:fix": "eslint src --ext .ts --fix",
      // Type checking
      "typecheck": "tsc --noEmit"
    },
    dependencies: {
      ...ormDeps,
      "fastify": "^5.8.3",
      "@fastify/cors": "^10.0.0",
      "@fastify/helmet": "^12.0.0",
      "@fastify/rate-limit": "^10.0.0",
      "@fastify/websocket": "^11.0.0",
      "eventemitter3": "^5.0.0",
      "zod": "^3.22.0",
      "dotenv": "^16.3.0",
      "commander": "^13.0.0",
      // AI-behavior whitelist deps — only included when the spec's step
      // text actually triggers them (predicted via predictAiBehaviorLibraries).
      // Pre-fix every backend installed all 5 libs unconditionally even
      // though 97% of generated bodies imported nothing. (#43K-B-review)
      ...buildAiLibraryDeps(spec, "runtime")
    },
    devDependencies: {
      "typescript": "^5.3.0",
      "@types/node": "^20.10.0",
      "tsx": "^4.7.0",
      ...ormDevDeps,
      "vitest": "^3.0.0",
      "@vitest/coverage-v8": "^3.0.0",
      "eslint": "^9.0.0",
      "@typescript-eslint/eslint-plugin": "^8.0.0",
      "@typescript-eslint/parser": "^8.0.0",
      // Type definitions for whichever AI-behavior whitelist libs are
      // included as runtime deps above. Same per-spec gating.
      ...buildAiLibraryDeps(spec, "types")
    },
    engines: {
      node: ">=20.0.0"
    }
  };
  return JSON.stringify(pkg, null, 2);
}
function buildAiLibraryDeps(spec, kind) {
  const out = {};
  const predicted = predictAiBehaviorLibraries(spec);
  for (const lib of predicted) {
    const versions = AI_LIBRARY_VERSIONS[lib];
    if (!versions) continue;
    if (kind === "runtime") {
      if (versions.runtime === "*") continue;
      out[lib] = versions.runtime;
    } else if (kind === "types" && versions.types) {
      out[`@types/${lib}`] = versions.types;
    }
  }
  return out;
}
export {
  generateBackendPackageJson as default
};
