import routeRegistry from './public-route-registry.json'
import publicSearchPolicy from './public-search-policy.json'

export type PublicRouteDefinition = {
  path: string
  label: string
  loaderTitle: string
  loaderEyebrow?: string
  loaderDescription?: string
  nav: boolean
  footer: boolean
  crawlable: boolean
}

type PublicSearchPolicyDefinition = {
  baseUrl: string
  explicitDisallowPaths: string[]
}

export const publicRouteRegistry = routeRegistry as PublicRouteDefinition[]
export const searchCrawlerPolicy = publicSearchPolicy as PublicSearchPolicyDefinition

function uniqueTrimmedPaths(paths: readonly string[]) {
  const result: string[] = []
  const seen = new Set<string>()

  for (const rawPath of paths) {
    const path = String(rawPath || '').trim()
    if (!path || seen.has(path)) {
      continue
    }

    seen.add(path)
    result.push(path)
  }

  return result
}

export const marketingNavLinks = publicRouteRegistry
  .filter((route) => route.nav)
  .map((route) => ({
    to: route.path,
    label: route.label,
  }))

export const footerLinks = publicRouteRegistry
  .filter((route) => route.footer)
  .map((route) => ({
    to: route.path,
    label: route.label,
  }))

export const crawlablePublicRoutes = publicRouteRegistry.filter((route) => route.crawlable)
export const nonCrawlablePublicRoutes = publicRouteRegistry.filter((route) => !route.crawlable)
export const publicSearchBaseUrl = String(searchCrawlerPolicy.baseUrl || '').trim().replace(/\/$/, '') || 'https://hypertwist.app'
export const publicCrawlerDisallowPaths = uniqueTrimmedPaths([
  ...(searchCrawlerPolicy.explicitDisallowPaths || []),
  ...nonCrawlablePublicRoutes.map((route) => route.path),
])

export function buildPublicSitemapXml(baseUrl = publicSearchBaseUrl) {
  const normalizedBaseUrl = baseUrl.replace(/\/$/, '')
  const urlEntries = crawlablePublicRoutes
    .map((route) => `  <url>\n    <loc>${normalizedBaseUrl}${route.path === '/' ? '/' : route.path}</loc>\n  </url>`)
    .join('\n')

  return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urlEntries}\n</urlset>\n`
}

export function buildPublicRobotsTxt(baseUrl = publicSearchBaseUrl) {
  const normalizedBaseUrl = baseUrl.replace(/\/$/, '')

  return [
    'User-agent: *',
    'Allow: /',
    ...publicCrawlerDisallowPaths.map((path) => `Disallow: ${path}`),
    '',
    `Sitemap: ${normalizedBaseUrl}/sitemap.xml`,
    '',
  ].join('\n')
}
