import { NextRequest, NextResponse } from 'next/server'
import { readFileSync, existsSync } from 'fs'
import { join, isAbsolute } from 'path'
import matter from 'gray-matter'
import { serialize } from 'next-mdx-remote/serialize'
import remarkGfm from 'remark-gfm'
import rehypeSlug from 'rehype-slug'
// Note: rehype-pretty-code is dynamically imported to handle serverless environments
// where shiki may not be fully available
import { getProjectFile } from '@/lib/storage/blob'

const STARTER_PATH = process.env.STARTER_PATH || 'devdoc-docs'

// Helper to get content root - supports both relative and absolute paths
function getContentRoot(): string {
  if (isAbsolute(STARTER_PATH)) {
    return STARTER_PATH
  }
  return join(process.cwd(), STARTER_PATH)
}

// Shiki theme options for syntax highlighting
const prettyCodeOptions = {
  theme: 'github-dark',
  keepBackground: true,
  defaultLang: 'plaintext',
}

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const slug = searchParams.get('slug')
  const is404Request = searchParams.get('is404') === 'true'
  
  if (!slug) {
    return NextResponse.json(
      { error: 'Missing slug parameter' },
      { status: 400 }
    )
  }
  
  // Check for multi-tenant mode (project slug from middleware)
  const projectSlug = request.headers.get('x-devdoc-project')
  
  // If multi-tenant, fetch from Blob Storage
  if (projectSlug && !projectSlug.startsWith('custom:')) {
    return handleMultiTenantDocs(projectSlug, slug, is404Request)
  }
  
  try {
    const starterDir = getContentRoot()
    
    // Try .mdx then .md
    let fullPath = join(starterDir, `${slug}.mdx`)
    if (!existsSync(fullPath)) {
      fullPath = join(starterDir, `${slug}.md`)
    }
    
    if (!existsSync(fullPath)) {
      // For 404 page requests, return 404 status (not a server error)
      // The client will handle showing the default 404 if custom doesn't exist
      return NextResponse.json(
        { error: 'Page not found' },
        { status: 404 }
      )
    }
    
    const fileContent = readFileSync(fullPath, 'utf-8')
    const { data: frontmatter, content } = matter(fileContent)
    
    // Serialize MDX for client-side rendering
    // Note: rehype-pretty-code is dynamically imported to handle cases where shiki
    // may not be available in serverless environments
    let mdxSource
    try {
      // Try with syntax highlighting first
      const rehypePrettyCodeModule = await import('rehype-pretty-code')
      const rehypePrettyCode = rehypePrettyCodeModule.default
      
      mdxSource = await serialize(content, {
        mdxOptions: {
          remarkPlugins: [remarkGfm],
          rehypePlugins: [
            rehypeSlug,
            [rehypePrettyCode, prettyCodeOptions],
          ],
        },
        parseFrontmatter: false,
      })
    } catch (syntaxError) {
      // Fallback: serialize without syntax highlighting if shiki is unavailable
      console.warn('[Docs API] Syntax highlighting unavailable, using fallback:', syntaxError)
      mdxSource = await serialize(content, {
        mdxOptions: {
          remarkPlugins: [remarkGfm],
          rehypePlugins: [rehypeSlug],
        },
        parseFrontmatter: false,
      })
    }
    
    return NextResponse.json({
      slug,
      frontmatter: {
        title: frontmatter.title || slug,
        description: frontmatter.description,
        icon: frontmatter.icon,
        // Page mode and layout options
        mode: frontmatter.mode || 'default',
        hideHeader: frontmatter.hideHeader || false,
        fullWidth: frontmatter.fullWidth || false,
        background: frontmatter.background,
      },
      mdxSource,
      rawContent: content, // Include raw content for changelog version extraction
    })
  } catch (error) {
    console.error('[Docs API] Error loading page:', error)
    return NextResponse.json(
      { error: 'Failed to load page', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    )
  }
}

/**
 * Handle multi-tenant docs request - fetch from Blob Storage
 */
async function handleMultiTenantDocs(projectSlug: string, slug: string, is404Request: boolean = false): Promise<Response> {
  try {
    // Try .mdx then .md
    let fileContent = await getProjectFile(projectSlug, `${slug}.mdx`)
    if (!fileContent) {
      fileContent = await getProjectFile(projectSlug, `${slug}.md`)
    }
    
    if (!fileContent) {
      // For 404 page requests, return 404 status
      return NextResponse.json(
        { error: 'Page not found' },
        { status: 404 }
      )
    }
    
    const { data: frontmatter, content } = matter(fileContent)
    
    // Serialize MDX for client-side rendering
    // Note: rehype-pretty-code is dynamically imported to handle cases where shiki
    // may not be available in serverless environments
    let mdxSource
    try {
      // Try with syntax highlighting first
      const rehypePrettyCodeModule = await import('rehype-pretty-code')
      const rehypePrettyCode = rehypePrettyCodeModule.default
      
      mdxSource = await serialize(content, {
        mdxOptions: {
          remarkPlugins: [remarkGfm],
          rehypePlugins: [
            rehypeSlug,
            [rehypePrettyCode, prettyCodeOptions],
          ],
        },
        parseFrontmatter: false,
      })
    } catch (syntaxError) {
      // Fallback: serialize without syntax highlighting if shiki is unavailable
      console.warn('[Docs API] Multi-tenant syntax highlighting unavailable:', syntaxError)
      mdxSource = await serialize(content, {
        mdxOptions: {
          remarkPlugins: [remarkGfm],
          rehypePlugins: [rehypeSlug],
        },
        parseFrontmatter: false,
      })
    }
    
    return NextResponse.json({
      slug,
      frontmatter: {
        title: frontmatter.title || slug,
        description: frontmatter.description,
        icon: frontmatter.icon,
        // Page mode and layout options
        mode: frontmatter.mode || 'default',
        hideHeader: frontmatter.hideHeader || false,
        fullWidth: frontmatter.fullWidth || false,
        background: frontmatter.background,
      },
      mdxSource,
      rawContent: content,
      isMultiTenant: true,
      projectSlug,
    })
  } catch (error) {
    console.error('[Docs API] Multi-tenant error:', error)
    return NextResponse.json(
      { error: 'Failed to load page', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    )
  }
}
