import { writeFileSync } from 'node:fs';
import { archive, live, type Version } from './versions.mts';

// Settings

const nonBreakingSpace = ' ';
const gapAfterVersion = 1;
const gapAfterName = 4;
const repoUrl = 'https://github.com/stephenmatheis/stephenmatheis.com';
const siteName = 'stephenmatheis.com';
const instructionsHeading = 'To archive the live version';
const instructionsOrderedLines = [
    `Push ${backticks('main')} to a new branch named ${backticks('vNN/name')}.`,
    `In Vercel, add ${backticks('vN.stephenmatheis.com')} as a domain for that branch.`,
    `In ${backticks('scripts/versions.mts')}, move live into the archive object array, give it a name, then increment live's number.`,
    `Run ${backticks('npm run readme')}.`,
];
const commands = ['npm run dev', 'npm run build', 'npm run readme'];
const readmeUrl = new URL('../README.md', import.meta.url);
const versionsUrl = new URL('../VERSIONS.txt', import.meta.url);

// Versions

const newestFirst = [...archive].sort((a, b) => b.number - a.number);
const everyVersion = [live, ...newestFirst];

function siteUrl(version: Version) {
    return version === live ? 'https://stephenmatheis.com' : `https://v${version.number}.stephenmatheis.com`;
}

function codeUrl(version: Version) {
    return `${repoUrl}/tree/${version.branch}`;
}

// README.md

const versionColumnWidth = Math.max(...everyVersion.map((version) => `v${version.number}`.length));
const nameColumnWidth = Math.max(...everyVersion.map((version) => version.name.length));

function backticks(text: string) {
    return ``${text}``;
}

function padding(textLength: number, columnWidth: number, gap: number) {
    return nonBreakingSpace.repeat(columnWidth - textLength + gap);
}

function line(version: Version) {
    const label = `v${version.number}`;
    const versionLink = `[${label}](${siteUrl(version)})`;
    const nameLink = `[${version.name}](${siteUrl(version)})`;
    const codeLink = `[[code](${codeUrl(version)})]`;

    return `${versionLink}${padding(label.length, versionColumnWidth, gapAfterVersion)}${nameLink}${padding(version.name.length, nameColumnWidth, gapAfterName)}${codeLink}`;
}

const siteNameBlock = `<samp>${siteName}</samp>`;
const liveBlock = `<samp>${line(live)}</samp>`;
const archiveBlock = `<samp>${newestFirst.map(line).join('\\\n')}</samp>`;
const instructionsHeadingBlock = `${instructionsHeading}:\\\n`;
const instructionsOrderedLinesBlock = `${instructionsOrderedLines.map((step, index) => `${index + 1}\\. ${step}`).join('\\\n')}`;
const instructionsBlock = `<samp>${instructionsHeadingBlock}${instructionsOrderedLinesBlock}</samp>`;
const commandsBlock = `<samp>&grave;&grave;&grave;sh\\\n${commands.map((command) => `${nonBreakingSpace.repeat(4)}${command}`).join('\\\n')}\\\n&grave;&grave;&grave;</samp>`;
const updatedReadme = /*md*/ `
<!-- generated by scripts/readme.mts -->
<!-- markdownlint-disable-file MD013 MD033 MD041 -->

${siteNameBlock}

${liveBlock}

${archiveBlock}

${instructionsBlock}

${commandsBlock}
`;

// VERSIONS.txt

const tableHeadings = ['Version', 'Name', 'Link', 'Code'];
const tableRows = everyVersion.map((version) => [
    `v${version.number}`,
    version.name,
    siteUrl(version),
    codeUrl(version),
]);
const tableColumnWidths = tableHeadings.map((heading, column) =>
    Math.max(heading.length, ...tableRows.map((row) => row[column].length)),
);
const tableSeparator = tableColumnWidths.map((width) => '-'.repeat(width));

function tableLine(cells: string[]) {
    return `| ${cells.map((cell, column) => cell.padEnd(tableColumnWidths[column])).join(' | ')} |`;
}

const updatedVersions = `# Versions

${[tableHeadings, tableSeparator, ...tableRows].map(tableLine).join('\n')}
`;

// Write

writeFileSync(readmeUrl, updatedReadme.trim() + '\n');
writeFileSync(versionsUrl, updatedVersions);

console.log(`Wrote ${everyVersion.length} versions to README.md`);
console.log(`Wrote ${everyVersion.length} versions to VERSIONS.txt`);