// Planu — Web Fetcher: consultDocs orchestration
import { searchAndRegisterFramework, saveRegistry } from '../registry-updater.js';
import { loadDocsRegistry, findDocsEntry, setDocsRegistryCache, getStoredRegistryPath, } from './registry-loader.js';
import { fetchUrl } from './http-client.js';
import { extractTextContent, extractCodeBlocks, extractBestPractices, buildSummaryFromContent, buildPlaceholderSummary, buildPlaceholderExamples, buildPlaceholderBestPractices, } from './content-extractor.js';
export async function consultDocsImpl(topic, framework) {
    const registry = await loadDocsRegistry();
    const resolvedFramework = framework ?? 'unknown';
    let docsEntry = findDocsEntry(resolvedFramework, registry);
    if (!docsEntry && resolvedFramework !== 'unknown') {
        const result = await searchAndRegisterFramework(resolvedFramework, registry);
        if (result.found) {
            setDocsRegistryCache(result.registry);
            docsEntry = findDocsEntry(resolvedFramework, result.registry);
            try {
                await saveRegistry(getStoredRegistryPath(), result.registry);
            }
            catch {
                // Non-critical: registry update failed
            }
        }
    }
    const docsUrl = docsEntry
        ? docsEntry.search.replace('{topic}', encodeURIComponent(topic))
        : `https://www.google.com/search?q=${encodeURIComponent(`${resolvedFramework} ${topic} documentation`)}`;
    const baseUrl = docsEntry?.base ?? '';
    if (baseUrl) {
        const fetchResult = await fetchUrl(docsUrl);
        if (fetchResult) {
            const textContent = extractTextContent(fetchResult.content);
            const codeBlocks = extractCodeBlocks(fetchResult.content);
            const practices = extractBestPractices(fetchResult.content, topic);
            return {
                framework: resolvedFramework,
                topic,
                docsUrl,
                summary: buildSummaryFromContent(textContent, topic, resolvedFramework),
                codeExamples: codeBlocks.length > 0 ? codeBlocks : buildPlaceholderExamples(topic, resolvedFramework),
                bestPractices: practices.length > 0
                    ? practices
                    : buildPlaceholderBestPractices(topic, resolvedFramework),
                source: fetchResult.source,
                stale: false,
                fetchedAt: new Date().toISOString(),
            };
        }
    }
    return {
        framework: resolvedFramework,
        topic,
        docsUrl,
        summary: buildPlaceholderSummary(topic, resolvedFramework, baseUrl),
        codeExamples: buildPlaceholderExamples(topic, resolvedFramework),
        bestPractices: buildPlaceholderBestPractices(topic, resolvedFramework),
        source: 'local-fallback',
        stale: true,
        fetchedAt: new Date().toISOString(),
    };
}
//# sourceMappingURL=docs-fetcher.js.map