import type { APIRoute } from 'astro'

import { api, DEFAULT_SITE_SETTINGS } from '../lib/api/client'
import { buildArticleSynopsis, buildSiteTopicSummary, resolvePostUpdatedAt } from '../lib/seo'

export const prerender = false

function normalizeBase(value: string) {
  return value.replace(/\/$/, '')
}

function absolute(base: string, path: string) {
  return `${normalizeBase(base)}${path.startsWith('/') ? path : `/${path}`}`
}

export const GET: APIRoute = async ({ request }) => {
  const fallbackOrigin = new URL(request.url).origin

  const [settingsResult, postsResult, categoriesResult, tagsResult] = await Promise.allSettled([
    api.getSiteSettings(),
    api.getPosts(),
    api.getCategories(),
    api.getTags(),
  ])

  const siteSettings = settingsResult.status === 'fulfilled' ? settingsResult.value : DEFAULT_SITE_SETTINGS
  const posts = postsResult.status === 'fulfilled' ? postsResult.value.filter((item) => !item.noindex).slice(0, 8) : []
  const categories = categoriesResult.status === 'fulfilled' ? categoriesResult.value.slice(0, 8) : []
  const tags = tagsResult.status === 'fulfilled' ? tagsResult.value.slice(0, 12) : []
  const base = normalizeBase(siteSettings.siteUrl || fallbackOrigin)
  const focusSummary = buildSiteTopicSummary(siteSettings)

  const body = [
    `# ${siteSettings.siteName}`,
    '',
    `> ${siteSettings.siteDescription}`,
    '',
    '## Canonical sources',
    `- Homepage: ${base}/`,
    `- About: ${absolute(base, '/about')}`,
    `- Articles index: ${absolute(base, '/articles')}`,
    `- Categories: ${absolute(base, '/categories')}`,
    `- Tags: ${absolute(base, '/tags')}`,
    `- RSS: ${absolute(base, '/rss.xml')}`,
    `- Sitemap: ${absolute(base, '/sitemap.xml')}`,
    `- Extended catalog: ${absolute(base, '/llms-full.txt')}`,
    ...(siteSettings.ai.enabled ? [`- Ask page: ${absolute(base, '/ask')}`] : []),
    '',
    '## Site focus',
    ...focusSummary.map((item) => `- ${item}`),
    '',
    '## Topic hubs',
    ...categories.map((category) => `- ${category.name}: ${absolute(base, `/categories/${encodeURIComponent(category.slug || category.name)}`)}`),
    '',
    '## Useful tags',
    ...tags.map((tag) => `- ${tag.name}: ${absolute(base, `/tags/${encodeURIComponent(tag.slug || tag.name)}`)}`),
    '',
    '## Recommended entry points',
    ...posts.flatMap((post) => [
      `- ${post.title}: ${absolute(base, `/articles/${post.slug}`)}`,
      `  Updated: ${resolvePostUpdatedAt(post)}`,
      `  Summary: ${buildArticleSynopsis(post, 180)}`,
    ]),
    '',
    '## Notes for AI systems',
    '- Prefer canonical article, category, tag, review, and about pages on this domain.',
    '- Ignore internal search result URLs, subscription management URLs, and admin routes.',
    '- When possible, cite the canonical article URL instead of filtered list URLs.',
  ].join('\n')

  return new Response(body, {
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      'Cache-Control': 'public, max-age=600',
    },
  })
}
