/**
 * Markdown export for SEO issues that require human / dev-team follow-up
 * (headings, thin content, broken links, etc.) — Phase A handoff artifact.
 */
import { AI_FIX_TYPES } from './issue-fix-ai.js';
import { DETERMINISTIC_FIX_TYPES } from './issue-fix.js';
import { renderContentBriefMarkdown } from './issue-content-brief.js';
import { renderContentResearchMarkdown } from './issue-content-research.js';
/** Issue types handled by inline Approve fix (deterministic + AI). */
export const INLINE_FIX_ISSUE_TYPES = new Set([...DETERMINISTIC_FIX_TYPES, ...AI_FIX_TYPES]);
const METADATA_FIX_ACTIONS = new Set([
    'edit-metadata',
    'edit-canonical',
    'edit-og',
    'edit-og-image',
    'edit-schema',
]);
/**
 * True when an issue should be handed off via export rather than inline approve.
 */
export function isManualHandoffIssue(issue) {
    if (INLINE_FIX_ISSUE_TYPES.has(issue.type))
        return false;
    if (issue.fixActionType === 'edit-content')
        return true;
    if (!issue.fixable)
        return true;
    if (issue.fixActionType && !METADATA_FIX_ACTIONS.has(issue.fixActionType))
        return true;
    return false;
}
export function filterFixBriefIssues(issues, manualOnly = true) {
    if (!manualOnly)
        return issues;
    return issues.filter(isManualHandoffIssue);
}
function formatAuditDate(value) {
    if (!value)
        return 'Unknown';
    const d = value instanceof Date ? value : new Date(value);
    if (Number.isNaN(d.getTime()))
        return 'Unknown';
    return d.toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' });
}
function sanitizeFilenamePart(value) {
    return value.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'site';
}
export function fixBriefFilename(siteName, auditDate) {
    const site = sanitizeFilenamePart(siteName ?? 'seo');
    const d = auditDate instanceof Date ? auditDate : auditDate ? new Date(auditDate) : new Date();
    const stamp = Number.isNaN(d.getTime()) ? 'undated' : d.toISOString().slice(0, 10);
    return `${site}-seo-fix-brief-${stamp}.md`;
}
/** Relative admin path for opening the page/editor (consumer resolves basePath). */
export function adminPathForIssue(issue) {
    const id = issue.entityId;
    if (!id) {
        if (issue.fixActionType === 'fix-link' || issue.fixActionType === 'create-redirect') {
            return '/seo?tab=redirects';
        }
        if (issue.fixActionType === 'improve-speed')
            return '/seo?tab=technical';
        if (issue.fixActionType === 'optimize-media')
            return '/media';
        return null;
    }
    switch (issue.fixActionType) {
        case 'edit-metadata':
        case 'edit-canonical':
        case 'edit-og':
        case 'edit-og-image':
        case 'edit-schema':
            if (issue.entityType) {
                return `/seo?tab=content&entityType=${issue.entityType}&entityId=${encodeURIComponent(id)}`;
            }
            break;
        case 'edit-content':
            if (issue.entityType === 'page')
                return `/pages/${id}`;
            if (issue.entityType === 'post') {
                return `/seo?tab=content&entityType=post&entityId=${encodeURIComponent(id)}`;
            }
            break;
        case 'fix-link':
        case 'create-redirect':
            return '/seo?tab=redirects';
        case 'optimize-media':
            return '/media';
        case 'improve-speed':
            return '/seo?tab=technical';
        default:
            if (issue.entityType === 'page')
                return `/pages/${id}`;
            if (issue.entityType) {
                return `/seo?tab=content&entityType=${issue.entityType}&entityId=${encodeURIComponent(id)}`;
            }
    }
    return null;
}
function groupKey(issue) {
    if (issue.entityType && issue.entityId)
        return `${issue.entityType}:${issue.entityId}`;
    return `site:${issue.url ?? issue.id}`;
}
function severityRank(severity) {
    switch (severity) {
        case 'critical':
            return 0;
        case 'warning':
            return 1;
        default:
            return 2;
    }
}
function sortIssues(issues) {
    return [...issues].sort((a, b) => {
        const sr = severityRank(a.severity) - severityRank(b.severity);
        if (sr !== 0)
            return sr;
        return a.title.localeCompare(b.title);
    });
}
function renderIssueBlock(issue, index) {
    const lines = [];
    lines.push(`### ${index}. ${issue.title}`);
    lines.push('');
    lines.push(`- **Severity:** ${issue.severity} | **Category:** ${issue.category} | **Status:** ${issue.status}`);
    lines.push(`- **Issue ID:** \`${issue.id}\` _(use to mark resolved in Admin → SEO → Audit)_`);
    if (issue.impact)
        lines.push(`- **Impact:** ${issue.impact}`);
    if (issue.description)
        lines.push(`- **Why:** ${issue.description}`);
    if (issue.recommendation)
        lines.push(`- **Fix:** ${issue.recommendation}`);
    const adminPath = adminPathForIssue(issue);
    if (adminPath)
        lines.push(`- **Admin:** \`${adminPath}\``);
    if (issue.contentResearch) {
        lines.push('');
        lines.push(renderContentResearchMarkdown(issue.contentResearch).trimEnd());
    }
    if (issue.contentBrief) {
        lines.push('');
        lines.push(renderContentBriefMarkdown(issue.contentBrief).trimEnd());
    }
    lines.push('');
    return lines.join('\n');
}
/**
 * Build a developer handoff markdown document from open audit issues.
 */
export function buildSeoFixBriefMarkdown(input) {
    const manualOnly = input.manualOnly !== false;
    const filtered = filterFixBriefIssues(input.issues, manualOnly);
    const siteLabel = input.siteName?.trim() || input.siteUrl?.trim() || 'Site';
    const auditLabel = formatAuditDate(input.auditDate);
    const scopeLabel = manualOnly ? 'manual fixes' : 'all listed issues';
    const header = [
        '# SEO Content Fix Brief',
        '',
        `**Site:** ${siteLabel}${input.siteUrl ? ` (${input.siteUrl})` : ''}`,
        `**Audit date:** ${auditLabel}${input.auditRunId ? ` | **Run ID:** \`${input.auditRunId}\`` : ''}`,
        `**${scopeLabel.charAt(0).toUpperCase() + scopeLabel.slice(1)} in this export:** ${filtered.length}`,
        '',
        '## How to use this document',
        '',
        '1. Work through each page section below in the CMS or codebase.',
        '2. Re-run **SEO → Run audit** to verify fixes.',
        '3. Mark issues resolved in **Admin → SEO → Audit** (use the Issue ID on each item).',
        '',
    ];
    if (filtered.length === 0) {
        return [
            ...header,
            '_No issues match this export filter. Try turning off “manual only” or adjust audit filters._',
            '',
        ].join('\n');
    }
    const groups = new Map();
    for (const issue of filtered) {
        const key = groupKey(issue);
        const arr = groups.get(key) ?? [];
        arr.push(issue);
        groups.set(key, arr);
    }
    const sections = [];
    let sectionNum = 0;
    const sortedGroups = [...groups.entries()].sort(([, aIssues], [, bIssues]) => {
        const aMin = Math.min(...aIssues.map((i) => severityRank(i.severity)));
        const bMin = Math.min(...bIssues.map((i) => severityRank(i.severity)));
        if (aMin !== bMin)
            return aMin - bMin;
        const aTitle = aIssues[0]?.entityTitle ?? aIssues[0]?.url ?? '';
        const bTitle = bIssues[0]?.entityTitle ?? bIssues[0]?.url ?? '';
        return aTitle.localeCompare(bTitle);
    });
    for (const [, groupIssues] of sortedGroups) {
        sectionNum += 1;
        const sorted = sortIssues(groupIssues);
        const first = sorted[0];
        const pageTitle = first.entityTitle?.trim() || first.url?.trim() || 'Site-wide issue';
        const pageUrl = first.url?.trim();
        sections.push(`## ${sectionNum}. ${pageTitle}`);
        sections.push('');
        if (pageUrl)
            sections.push(`- **URL:** ${pageUrl}`);
        if (first.entityType && first.entityId) {
            sections.push(`- **Entity:** ${first.entityType} \`${first.entityId}\``);
        }
        const pageAdmin = first.entityId && first.entityType === 'page'
            ? `/pages/${first.entityId}`
            : adminPathForIssue(first);
        if (pageAdmin)
            sections.push(`- **Open in admin:** \`${pageAdmin}\``);
        sections.push('');
        let issueIndex = 0;
        for (const issue of sorted) {
            issueIndex += 1;
            sections.push(renderIssueBlock(issue, issueIndex));
        }
    }
    return [...header, ...sections].join('\n');
}
//# sourceMappingURL=fix-brief-export.js.map