import { existsSync } from 'node:fs'
import path from 'node:path'

function normalizeFlag(value: string | undefined) {
  return String(value || '').trim().toLowerCase()
}

function hasFileExtension(requestPath: string) {
  const lastSegment = requestPath.split('/').pop() || ''
  return /\.[a-z0-9]+$/i.test(lastSegment)
}

export interface StaticWebsiteConfig {
  enabled: boolean
  distPath: string
  indexHtmlPath: string
  reason: 'auto_found' | 'auto_missing' | 'forced_found' | 'forced_missing' | 'explicit_disabled'
}

export function resolveStaticWebsiteConfig(options?: {
  cwd?: string
  websiteDistPath?: string
  serveStaticWebsite?: string
}): StaticWebsiteConfig {
  const cwd = options?.cwd || process.cwd()
  const distPath = path.resolve(cwd, options?.websiteDistPath || '../dist')
  const indexHtmlPath = path.join(distPath, 'index.html')
  const serveFlag = normalizeFlag(options?.serveStaticWebsite)
  const hasIndexHtml = existsSync(indexHtmlPath)

  if (serveFlag === 'false' || serveFlag === '0' || serveFlag === 'no') {
    return {
      enabled: false,
      distPath,
      indexHtmlPath,
      reason: 'explicit_disabled',
    }
  }

  if (serveFlag === 'true' || serveFlag === '1' || serveFlag === 'yes') {
    return {
      enabled: hasIndexHtml,
      distPath,
      indexHtmlPath,
      reason: hasIndexHtml ? 'forced_found' : 'forced_missing',
    }
  }

  return {
    enabled: hasIndexHtml,
    distPath,
    indexHtmlPath,
    reason: hasIndexHtml ? 'auto_found' : 'auto_missing',
  }
}

export function shouldServeSpaFallback(requestPath: string) {
  if (!requestPath || requestPath === '/health') {
    return false
  }

  if (
    requestPath.startsWith('/api/')
    || requestPath === '/api'
    || requestPath.startsWith('/auth/')
    || requestPath === '/auth'
  ) {
    return false
  }

  if (hasFileExtension(requestPath)) {
    return false
  }

  return true
}
