/**
 * Bundle Component Analyzer
 * Analyzes the built bundle to see which components are actually included
 */

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

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

const DIST_DIR = path.join(__dirname, "../dist")
const ASSETS_DIR = path.join(DIST_DIR, "assets")

/**
 * Read all JS files from dist/assets
 */
const readBundleFiles = () => {
  if (!fs.existsSync(ASSETS_DIR)) {
    console.error("❌ Dist directory not found. Run `npm run build` first.")

    return []
  }

  const files = fs.readdirSync(ASSETS_DIR)
  const jsFiles = files.filter((file) => file.endsWith(".js"))

  console.log(`📦 Found ${jsFiles.length} JS bundle files:`)
  jsFiles.forEach((file) => console.log(`   - ${file}`))

  return jsFiles.map((file) => ({
    name: file,
    path: path.join(ASSETS_DIR, file),
    content: fs.readFileSync(path.join(ASSETS_DIR, file), "utf-8"),
  }))
}

/**
 * Search for Vue component references in bundle
 */
const searchForComponent = (bundleFiles, componentName) => {
  const results = []

  // Different patterns a Vue component might appear as in the bundle
  const patterns = [
    new RegExp(`${componentName}`, "gi"),
    new RegExp(`${componentName}\\.vue`, "gi"),
    new RegExp(`"${componentName}"`, "gi"),
    new RegExp(`'${componentName}'`, "gi"),
    new RegExp(`${componentName.toLowerCase()}`, "gi"),
    // Vue component compilation patterns
    new RegExp(`_component_${componentName}`, "gi"),
    new RegExp(`${componentName}_vue`, "gi"),
    new RegExp(`__default__.*${componentName}`, "gi"),
  ]

  bundleFiles.forEach((file) => {
    patterns.forEach((pattern, index) => {
      const matches = file.content.match(pattern)

      if (matches) {
        results.push({
          file: file.name,
          pattern: pattern.source,
          matches: matches.length,
          firstMatch: matches[0],
        })
      }
    })
  })

  return results
}

/**
 * List all likely Vue component references in bundle
 */
const findAllVueComponents = (bundleFiles) => {
  const componentPatterns = [
    // Look for .vue file references
    /[a-zA-Z0-9_-]+\.vue/gi,
    // Look for Vue component registration patterns
    /_component_[a-zA-Z0-9_]+/gi,
    // Look for defineComponent calls
    /defineComponent\s*\(/gi,
    // Look for component imports
    /import.*from.*\.vue/gi,
  ]

  const allComponents = new Set()

  bundleFiles.forEach((file) => {
    componentPatterns.forEach((pattern) => {
      const matches = file.content.match(pattern)

      if (matches) {
        matches.forEach((match) => allComponents.add(match))
      }
    })
  })

  return Array.from(allComponents)
}

/**
 * Check if routes are properly bundled
 */
const analyzeRoutes = (bundleFiles) => {
  const routePatterns = [
    /ProductOrchestrator/gi,
    /public_terms/gi,
    /"app\.space\.page"/gi,
    /"public\.logout"/gi,
    /"public\.terms"/gi,
    /vue-router/gi,
    /createRouter/gi,
  ]

  const routeResults = {}

  routePatterns.forEach((pattern) => {
    const patternName = pattern.source.replace(/[^a-zA-Z0-9]/g, "_")

    routeResults[patternName] = []

    bundleFiles.forEach((file) => {
      const matches = file.content.match(pattern)

      if (matches) {
        routeResults[patternName].push({
          file: file.name,
          matches: matches.length,
        })
      }
    })
  })

  return routeResults
}

/**
 * Main analysis function
 */
const analyzeBundle = () => {
  console.log("🔍 Analyzing bundle for Vue components...\n")

  const bundleFiles = readBundleFiles()

  if (bundleFiles.length === 0) {
    return
  }

  console.log("\n📊 Bundle Analysis Results:")
  console.log("=====================================")

  // Check for ProductOrchestrator specifically
  console.log("\n🎭 ProductOrchestrator Analysis:")
  const orchestratorResults = searchForComponent(
    bundleFiles,
    "ProductOrchestrator",
  )

  if (orchestratorResults.length > 0) {
    console.log("✅ ProductOrchestrator found in bundle:")
    orchestratorResults.forEach((result) => {
      console.log(
        `   📁 ${result.file}: ${result.matches} matches (${result.pattern})`,
      )
    })
  } else {
    console.log("❌ ProductOrchestrator NOT found in bundle!")
  }

  // Check other critical components
  const criticalComponents = ["App", "public_terms", "GridDefaultPage"]

  criticalComponents.forEach((component) => {
    console.log(`\n🔍 ${component} Analysis:`)
    const results = searchForComponent(bundleFiles, component)

    if (results.length > 0) {
      console.log(`✅ ${component} found:`)
      results.forEach((result) => {
        console.log(`   📁 ${result.file}: ${result.matches} matches`)
      })
    } else {
      console.log(`❌ ${component} NOT found in bundle!`)
    }
  })

  // Analyze routes
  console.log("\n🛣️  Route Analysis:")
  const routeResults = analyzeRoutes(bundleFiles)

  Object.entries(routeResults).forEach(([pattern, results]) => {
    if (results.length > 0) {
      console.log(`✅ ${pattern}: Found in ${results.length} files`)
    } else {
      console.log(`❌ ${pattern}: Not found`)
    }
  })

  // Show all Vue components found
  console.log("\n📋 All Vue Component References Found:")
  const allComponents = findAllVueComponents(bundleFiles)

  if (allComponents.length > 0) {
    allComponents.slice(0, 20).forEach((comp) => console.log(`   - ${comp}`))
    if (allComponents.length > 20) {
      console.log(`   ... and ${allComponents.length - 20} more`)
    }
  } else {
    console.log("   ❌ No Vue component references found!")
  }

  // Bundle size info
  console.log("\n📏 Bundle Size Info:")
  let totalSize = 0

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

    totalSize += stats.size
    console.log(`   📁 ${file.name}: ${sizeKB} KB`)
  })
  console.log(`   📊 Total: ${Math.round(totalSize / 1024)} KB`)

  return {
    orchestratorFound: orchestratorResults.length > 0,
    bundleFiles: bundleFiles.length,
    totalComponents: allComponents.length,
    totalSize: Math.round(totalSize / 1024),
  }
}

// Run analysis if script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
  analyzeBundle()
}

export default analyzeBundle
