import { NextResponse } from 'next/server';
import { join } from 'path';
import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
/**
 * sitemap.xml - Auto-generated sitemap for search engines
 * 
 * Generated from docs.json configuration.
 * Private tabs and groups are excluded from the sitemap.
 */ const DOCS_DIR = join(process.cwd(), 'templates', 'starter');
const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
function loadDocsConfig() {
    const configPath = join(DOCS_DIR, 'docs.json');
    if (!existsSync(configPath)) return null;
    try {
        const content = readFileSync(configPath, 'utf-8');
        return JSON.parse(content);
    } catch  {
        return null;
    }
}
function getFileLastModified(slug) {
    const extensions = [
        '.mdx',
        '.md'
    ];
    for (const ext of extensions){
        const filePath = join(DOCS_DIR, `${slug}${ext}`);
        if (existsSync(filePath)) {
            try {
                const stats = statSync(filePath);
                return stats.mtime.toISOString().split('T')[0];
            } catch  {
                return undefined;
            }
        }
    }
    return undefined;
}
function getChangelogFiles() {
    const changelogDir = join(DOCS_DIR, 'changelog');
    if (!existsSync(changelogDir)) return [];
    try {
        return readdirSync(changelogDir).filter((f)=>(f.endsWith('.mdx') || f.endsWith('.md')) && f !== 'latest.mdx').map((f)=>f.replace(/\.(mdx?|md)$/, ''));
    } catch  {
        return [];
    }
}
function generateSitemap(config) {
    const entries = [];
    const baseUrl = config.seo?.metatags?.canonical || BASE_URL;
    // Add homepage
    entries.push({
        url: baseUrl,
        changefreq: 'weekly',
        priority: 1.0
    });
    // Process navigation tabs (skip private tabs)
    if (config.navigation?.tabs) {
        for (const tab of config.navigation.tabs){
            // Skip private tabs - they should not appear in sitemap
            if (tab.visibility === 'private') {
                continue;
            }
            if (tab.type === 'docs' && tab.groups) {
                for (const group of tab.groups){
                    // Skip private groups
                    if (group.visibility === 'private') {
                        continue;
                    }
                    for (const page of group.pages){
                        const lastmod = getFileLastModified(page);
                        const urlPath = page === 'index' ? '' : page;
                        entries.push({
                            url: `${baseUrl}/#${tab.tab.toLowerCase()}/page/${urlPath}`.replace(/\/+$/, ''),
                            lastmod,
                            changefreq: 'weekly',
                            priority: page === 'index' ? 0.9 : 0.8
                        });
                    }
                }
            } else if (tab.type === 'openapi') {
                entries.push({
                    url: `${baseUrl}/#api-reference`,
                    changefreq: 'weekly',
                    priority: 0.9
                });
            } else if (tab.type === 'changelog') {
                entries.push({
                    url: `${baseUrl}/#changelog`,
                    changefreq: 'weekly',
                    priority: 0.7
                });
                // Add individual changelog pages
                const versions = getChangelogFiles();
                for (const version of versions){
                    const lastmod = getFileLastModified(`changelog/${version}`);
                    entries.push({
                        url: `${baseUrl}/#changelog/page/changelog/${version}`,
                        lastmod,
                        changefreq: 'monthly',
                        priority: 0.6
                    });
                }
            }
        // Note: graphql tabs are skipped since they don't have individual pages
        }
    }
    // Generate XML
    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${entries.map((entry)=>`  <url>
    <loc>${escapeXml(entry.url)}</loc>
${entry.lastmod ? `    <lastmod>${entry.lastmod}</lastmod>\n` : ''}${entry.changefreq ? `    <changefreq>${entry.changefreq}</changefreq>\n` : ''}${entry.priority !== undefined ? `    <priority>${entry.priority}</priority>\n` : ''}  </url>`).join('\n')}
</urlset>`;
    return xml;
}
function escapeXml(str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
}
export async function GET() {
    try {
        // Check for custom sitemap.xml first
        const customPath = join(DOCS_DIR, 'sitemap.xml');
        if (existsSync(customPath)) {
            const customContent = readFileSync(customPath, 'utf-8');
            return new NextResponse(customContent, {
                headers: {
                    'Content-Type': 'application/xml; charset=utf-8',
                    'Cache-Control': 'public, max-age=3600'
                }
            });
        }
        // Generate from docs.json config
        const config = loadDocsConfig();
        if (!config) {
            return new NextResponse('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>', {
                headers: {
                    'Content-Type': 'application/xml; charset=utf-8'
                }
            });
        }
        const content = generateSitemap(config);
        return new NextResponse(content, {
            headers: {
                'Content-Type': 'application/xml; charset=utf-8',
                'Cache-Control': 'public, max-age=3600'
            }
        });
    } catch (error) {
        console.error('Error generating sitemap.xml:', error);
        return new NextResponse('Error generating sitemap.xml', {
            status: 500
        });
    }
}
