/**
 * Simple Bundle Check (Plain JavaScript)
 * Quick check if ProductOrchestrator is in the bundle
 */

import fs from "fs"
import path from "path"
import { fileURLToPath } from "url"

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

console.log("🔍 Simple Bundle Check for ProductOrchestrator\n")

// Check if dist exists
const distDir = path.join("/app/dist")

if (!fs.existsSync(distDir)) {
  console.log("❌ No dist directory found. Run `npm run build` first.")
  process.exit(1)
}

// Find all JavaScript files in dist
const findJsFiles = (dir) => {
  const files = []
  const items = fs.readdirSync(dir, { withFileTypes: true })

  for (const item of items) {
    const fullPath = path.join(dir, item.name)

    if (item.isDirectory()) {
      files.push(...findJsFiles(fullPath))
    } else if (item.name.endsWith(".js")) {
      files.push(fullPath)
    }
  }

  return files
}

const jsFiles = findJsFiles(distDir)

console.log(`📦 Found ${jsFiles.length} JavaScript files in dist/`)

let orchestratorFound = false
let totalSize = 0

jsFiles.forEach((file) => {
  const stats = fs.statSync(file)
  const sizeKB = Math.round(stats.size / 1024)

  totalSize += stats.size

  const relativePath = path.relative(distDir, file)

  console.log(`   📁 ${relativePath} (${sizeKB} KB)`)

  // Check file content for ProductOrchestrator
  const content = fs.readFileSync(file, "utf-8")
  const patterns = [
    "ProductOrchestrator",
    "productorchestrator",
    "product-orchestrator",
    "ProductOrchestrator.vue",
  ]

  const found = patterns.some((pattern) => content.includes(pattern))

  if (found) {
    orchestratorFound = true
    console.log(`      ✅ ProductOrchestrator found in this file!`)

    // Show some context
    const lines = content.split("\n")

    lines.forEach((line, index) => {
      if (patterns.some((p) => line.includes(p))) {
        console.log(
          `         Line ${index + 1}: ${line.trim().substring(0, 100)}...`,
        )
      }
    })
  }
})

console.log(`\n📊 Total bundle size: ${Math.round(totalSize / 1024)} KB`)
console.log(
  `🎭 ProductOrchestrator in bundle: ${orchestratorFound ? "✅ YES" : "❌ NO"}`,
)

if (!orchestratorFound) {
  console.log("\n🚨 ProductOrchestrator NOT found in bundle!")
  console.log("💡 Possible causes:")
  console.log("   1. Route import failed")
  console.log("   2. Component has syntax errors")
  console.log("   3. Tree-shaking removed it")
  console.log("   4. Build configuration issue")
  console.log("\n🔧 Try these steps:")
  console.log("   1. npm run debug-router")
  console.log("   2. npm run build -- --debug")
  console.log("   3. Check your routes.ts file")
} else {
  console.log("\n✅ ProductOrchestrator found in bundle - route should work!")
}
