/**
 * Removes code blocks from cahier des charges:
 * - Lua blocks (-- path, local ..., return Module)
 * - weightedPick function block
 * - Console/stack trace blocks
 */
const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, '..', 'docs', 'cahier des charges.md');
let lines = fs.readFileSync(filePath, 'utf8').split('\n');
const out = [];
let i = 0;
const n = lines.length;

function isLuaBlockStart(line) {
  return (
    line.startsWith('-- ReplicatedStorage/') ||
    line.startsWith('-- ServerScriptService/')
  );
}

function isLuaBlockEnd(line, forServerMain) {
  if (forServerMain) {
    return line === 'end)';
  }
  return (
    line === 'return LootTables' ||
    line === 'return PlayerDataService' ||
    line === 'return ZooService' ||
    line === 'return IncomeService'
  );
}

function isStackTraceLine(line) {
  if (!line || line.trim() === '') return false;
  return (
    /^\d{2}:\d{2}:\d{2}\.\d+ /.test(line) ||
    /\.(js|ts):\d+/.test(line) ||
    /^at \w+ \(/.test(line) ||
    /^(GET|POST) https:\/\//.test(line) ||
    /Fetch failed loading/.test(line) ||
    /^[a-zA-Z]+ @ (main|api-client|auth-client)\.js:\d+/.test(line) ||
    /^await in /.test(line) ||
    /\(anonymous\) @ /.test(line) ||
    /^Error: /.test(line) && /\.js:\d+/.test(line)
  );
}

while (i < n) {
  const line = lines[i];

  // Lua block: -- ReplicatedStorage/ or -- ServerScriptService/
  if (isLuaBlockStart(line)) {
    const forServerMain = line.includes('ServerMain');
    i++;
    while (i < n && !isLuaBlockEnd(lines[i], forServerMain)) {
      i++;
    }
    if (i < n) i++;
    continue;
  }

  // weightedPick function block
  if (line.startsWith('local function weightedPick(rng, entries)')) {
    i++;
    while (i < n && lines[i] !== 'end') {
      i++;
    }
    if (i < n) i++;
    continue;
  }

  // task.spawn(function() ... end) block (leftover Lua fragment)
  if (line === 'task.spawn(function()') {
    i++;
    while (i < n && lines[i] !== 'end)') {
      i++;
    }
    if (i < n) i++;
    continue;
  }

  // Consecutive stack trace lines
  if (isStackTraceLine(line)) {
    while (i < n && isStackTraceLine(lines[i])) {
      i++;
    }
    continue;
  }

  out.push(line);
  i++;
}

fs.writeFileSync(filePath, out.join('\n'));
console.log('Removed code blocks. Lines: ' + lines.length + ' -> ' + out.length);
