#!/usr/bin/env node
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { dirname, extname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const scriptDir = dirname(fileURLToPath(import.meta.url));
const docsRoot = resolve(scriptDir, '..');
const contentRoot = resolve(docsRoot, 'content/docs');
const publicRoot = resolve(docsRoot, 'public');
const allowedUtilityRoutes = new Set(['/api/search', '/llms.txt', '/llms-full.txt']);
const pageFiles = [];

function walk(dir) {
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
    const full = join(dir, entry.name);
    if (entry.isDirectory()) {
      walk(full);
    } else if (['.md', '.mdx'].includes(extname(entry.name)) && entry.name !== 'meta.json') {
      pageFiles.push(full);
    }
  }
}

function routeFor(file) {
  const rel = relative(contentRoot, file).replace(/\\/g, '/');
  const withoutExt = rel.replace(/\.(md|mdx)$/, '');
  const route = withoutExt.endsWith('/index')
    ? withoutExt.slice(0, -'/index'.length)
    : withoutExt;

  return `/${route}`.replace(/\/+$/, '') || '/';
}

walk(contentRoot);

const routes = new Set(pageFiles.map(routeFor));
const errors = [];
const markdownLink = /!?\[[^\]]*\]\(([^)]+)\)/g;
const mdxHref = /\bhref=["']([^"']+)["']/g;

function cleanTarget(target) {
  return target
    .trim()
    .replace(/^<|>$/g, '')
    .split('#')[0]
    .split('?')[0];
}

function checkAbsolute(target, file) {
  if (!target || target.startsWith('http:') || target.startsWith('https:') || target.startsWith('mailto:')) {
    return;
  }

  if (!target.startsWith('/')) return;
  if (allowedUtilityRoutes.has(target)) return;

  if (target.startsWith('/llms.mdx/')) return;

  const publicPath = join(publicRoot, target);
  if (existsSync(publicPath)) return;

  const route = target.endsWith('.md') ? target.slice(0, -3) || '/' : target;
  if (!routes.has(route)) {
    errors.push(`${relative(docsRoot, file)} -> ${target}`);
  }
}

for (const file of pageFiles) {
  const content = readFileSync(file, 'utf8');
  for (const match of content.matchAll(markdownLink)) {
    checkAbsolute(cleanTarget(match[1]), file);
  }
  for (const match of content.matchAll(mdxHref)) {
    checkAbsolute(cleanTarget(match[1]), file);
  }
}

if (errors.length > 0) {
  console.error('Links internos quebrados:');
  for (const error of errors) console.error(`- ${error}`);
  process.exit(1);
}

console.log(`Links internos OK (${routes.size} páginas).`);
