/**
 * Router Debug Script
 * Checks if routes are properly configured and components are importable
 */

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

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

/**
 * Check if files exist
 */
const checkFileExistence = () => {
  console.log("📁 Checking file existence...\n")

  const filesToCheck = [
    {
      name: "routes.ts",
      path: path.resolve(__dirname, "../router/routes.ts"),
    },
    {
      name: "router/index.ts",
      path: path.resolve(__dirname, "../router/index.ts"),
    },
    {
      name: "ProductOrchestrator.vue",
      path: path.resolve(__dirname, "../ProductOrchestrator.vue"),
    },
    { name: "App.vue", path: path.resolve(__dirname, "../App.vue") },
    { name: "main.ts", path: path.resolve(__dirname, "../main.ts") },
    { name: "index.ts", path: path.resolve(__dirname, "../index.ts") },
  ]

  const results = {}

  filesToCheck.forEach((file) => {
    const exists = fs.existsSync(file.path)

    results[file.name] = { exists, path: file.path }
    console.log(`   ${exists ? "✅" : "❌"} ${file.name}: ${file.path}`)

    if (exists && file.name.endsWith(".ts")) {
      // Try to read first few lines for basic syntax check
      try {
        const content = fs.readFileSync(file.path, "utf-8")
        const lines = content.split("\n").slice(0, 5)

        console.log(`      📝 First lines:`)
        lines.forEach((line, i) => {
          if (line.trim()) console.log(`         ${i + 1}: ${line.trim()}`)
        })
      } catch (error) {
        console.log(`      ❌ Could not read file: ${error.message}`)
      }
    }
  })

  return results
}

/**
 * Analyze routes.ts content
 */
const analyzeRoutesContent = () => {
  console.log("\n📝 Analyzing routes.ts content...")

  const routesPath = path.resolve(__dirname, "../router/routes.ts")

  if (!fs.existsSync(routesPath)) {
    console.log("❌ routes.ts not found")

    return null
  }

  try {
    const content = fs.readFileSync(routesPath, "utf-8")

    // Check for imports
    const importLines = content
      .split("\n")
      .filter((line) => line.trim().startsWith("import"))

    console.log(`   📦 Found ${importLines.length} import statements:`)
    importLines.forEach((line) => console.log(`      ${line.trim()}`))

    // Check for ProductOrchestrator
    const hasProductOrchestrator = content.includes("ProductOrchestrator")

    console.log(
      `   🎭 ProductOrchestrator referenced: ${hasProductOrchestrator ? "✅" : "❌"}`,
    )

    // Check for export
    const hasExport = content.includes("export default")

    console.log(`   📤 Has default export: ${hasExport ? "✅" : "❌"}`)

    // Count routes
    const routeCount = (content.match(/\{[\s\S]*?path:/g) || []).length

    console.log(`   🛣️  Estimated route count: ${routeCount}`)

    return {
      hasProductOrchestrator,
      hasExport,
      routeCount,
      importCount: importLines.length,
    }
  } catch (error) {
    console.log(`❌ Could not analyze routes.ts: ${error.message}`)

    return null
  }
}

/**
 * Check Vite configuration
 */
const checkViteConfig = () => {
  console.log("\n⚙️  Checking Vite configuration...")

  const viteConfigPath = path.resolve(__dirname, "../vite.config.ts")

  if (!fs.existsSync(viteConfigPath)) {
    console.log("❌ vite.config.ts not found")

    return
  }

  try {
    const content = fs.readFileSync(viteConfigPath, "utf-8")

    // Check for important settings
    const checks = [
      { name: "Vue plugin", pattern: /@vitejs\/plugin-vue|vue\(\)/ },
      { name: "TypeScript support", pattern: /\.ts/ },
      { name: "Alias configuration", pattern: /alias:|resolve:/ },
      { name: "Build configuration", pattern: /build:/ },
      { name: "Router import", pattern: /ProductOrchestrator|router/ },
    ]

    checks.forEach((check) => {
      const found = new RegExp(check.pattern).test(content)

      console.log(`   ${found ? "✅" : "❌"} ${check.name}`)
    })
  } catch (error) {
    console.log(`❌ Could not read vite.config.ts: ${error.message}`)
  }
}

/**
 * Check package.json for TypeScript setup
 */
const checkTypeScriptSetup = () => {
  console.log("\n📦 Checking TypeScript setup...")

  const packageJsonPath = path.resolve(__dirname, "../package.json")

  if (!fs.existsSync(packageJsonPath)) {
    console.log("❌ package.json not found")

    return
  }

  try {
    const content = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"))

    // Check for TypeScript dependencies
    const allDeps = {
      ...content.dependencies,
      ...content.devDependencies,
    }

    const tsChecks = ["typescript", "vue-tsc", "@vitejs/plugin-vue", "vite"]

    tsChecks.forEach((dep) => {
      const version = allDeps[dep]

      console.log(
        `   ${version ? "✅" : "❌"} ${dep}: ${version || "not found"}`,
      )
    })

    // Check scripts
    console.log("\n   📜 Build scripts:")
    const scripts = content.scripts || {}

    Object.entries(scripts).forEach(([name, script]) => {
      if (name.includes("build") || name.includes("dev")) {
        console.log(`      ${name}: ${script}`)
      }
    })
  } catch (error) {
    console.log(`❌ Could not read package.json: ${error.message}`)
  }
}

/**
 * Check main app imports
 */
const testMainAppImports = async () => {
  console.log("\n📱 Testing main app imports...")

  try {
    // Test main.ts
    console.log("   Testing main.ts...")
    const main = await import("../main.ts")

    console.log("   ✅ main.ts imported successfully")

    // Test App.vue
    console.log("   Testing App.vue...")
    const app = await import("../App.vue")

    console.log("   ✅ App.vue imported successfully")
    console.log(`      Default export: ${!!app.default}`)

    // Test index.ts
    console.log("   Testing index.ts...")
    const index = await import("../index.ts")

    console.log("   ✅ index.ts imported successfully")
  } catch (error) {
    console.error("❌ Main app import failed:", error.message)
  }
}

/**
 * Main debug function
 */
const debugRouter = async () => {
  console.log("🐛 Router Debug Analysis")
  console.log("========================\n")

  await testRouteImports()
  await testRouterCreation()
  await testMainAppImports()

  console.log("\n💡 Debugging Tips:")
  console.log(
    "   1. If ProductOrchestrator import fails: Check file path and existence",
  )
  console.log("   2. If routes are empty: Check routes.ts export")
  console.log("   3. If router creation fails: Check router/index.ts")
  console.log("   4. Run `npm run build --debug` to see Vite's perspective")
}

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

export default debugRouter
