/**
 * URL Fetch API
 *
 * POST /api/fetch-url — fetch a URL and extract readable text content
 */
export async function registerUrlRoutes(fastify) {
    fastify.post('/api/fetch-url', async (req, reply) => {
        const { url } = req.body || {};
        if (!url || typeof url !== 'string') {
            return reply.status(400).send({ error: 'url is required' });
        }
        // Basic URL validation
        let parsed;
        try {
            parsed = new URL(url);
        }
        catch {
            return reply.status(400).send({ error: 'Invalid URL' });
        }
        if (!['http:', 'https:'].includes(parsed.protocol)) {
            return reply.status(400).send({ error: 'Only HTTP/HTTPS URLs are supported' });
        }
        try {
            const response = await fetch(url, {
                headers: {
                    'User-Agent': 'Studiograph/1.0 (knowledge graph import)',
                    'Accept': 'text/html,application/xhtml+xml,text/plain',
                },
                signal: AbortSignal.timeout(15000),
            });
            if (!response.ok) {
                return reply.status(502).send({ error: `Failed to fetch: ${response.status} ${response.statusText}` });
            }
            const contentType = response.headers.get('content-type') ?? '';
            const html = await response.text();
            // Plain text — return directly
            if (contentType.includes('text/plain')) {
                return reply.send({ url, title: parsed.hostname, text: html.trim() });
            }
            // HTML — extract readable content via Readability
            const { parseHTML } = await import('linkedom');
            const { Readability } = await import('@mozilla/readability');
            const { document } = parseHTML(html);
            const reader = new Readability(document);
            const article = reader.parse();
            if (article?.textContent) {
                return reply.send({
                    url,
                    title: article.title || parsed.hostname,
                    text: article.textContent.trim(),
                });
            }
            // Fallback: strip tags manually
            const text = html
                .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
                .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
                .replace(/<[^>]+>/g, ' ')
                .replace(/\s+/g, ' ')
                .trim();
            return reply.send({
                url,
                title: parsed.hostname,
                text: text.slice(0, 50000), // cap at 50k chars
            });
        }
        catch (err) {
            if (err.name === 'TimeoutError' || err.name === 'AbortError') {
                return reply.status(504).send({ error: 'URL fetch timed out' });
            }
            return reply.status(502).send({ error: err.message ?? 'Failed to fetch URL' });
        }
    });
}
//# sourceMappingURL=url-api.js.map