const fs = require('fs');
const path = require('path');

const ROOT = path.resolve(__dirname, '..');
const OUT_ROOT = path.join(ROOT, 'docs', 'generated-formula-libraries', 'domains');

const DOMAINS = [
  {
    id: 'geography-navigation-maps',
    title: 'Geography Navigation Maps',
    branches: ['geodesy', 'map-projection', 'route-navigation', 'terrain-contours', 'remote-sensing-grid', 'urban-road-network', 'hydrology-network', 'satellite-orbit', 'magnetic-anomaly', 'spatial-buffer'],
  },
  {
    id: 'chemistry',
    title: 'Chemistry',
    branches: ['stoichiometry', 'acid-base-equilibrium', 'redox', 'reaction-kinetics', 'chemical-thermodynamics', 'electrochemistry', 'organic-reaction', 'polymerization', 'enzyme-catalysis', 'surface-adsorption'],
  },
  {
    id: 'computer-science',
    title: 'Computer Science',
    branches: ['algorithm-complexity', 'data-structures', 'automata', 'graph-algorithms', 'hashing', 'cryptographic-protocols', 'concurrency', 'database-indexing', 'distributed-consensus', 'formal-verification'],
  },
  {
    id: 'economics-game-systems',
    title: 'Economics Game Systems',
    branches: ['supply-demand', 'auction-mechanism', 'game-equilibrium', 'portfolio-risk', 'order-book', 'liquidity-pool', 'mechanism-design', 'market-impact', 'credit-scoring', 'dynamic-programming'],
  },
  {
    id: 'board-games',
    title: 'Board Games',
    branches: ['go-connectivity', 'xiangqi-rules', 'chess-rules', 'shogi-rules', 'gomoku', 'othello', 'sudoku', 'minesweeper', 'maze-routing', 'tetris-state'],
  },
  {
    id: 'biology',
    title: 'Biology',
    branches: ['cell-division', 'dna-sequence', 'protein-folding', 'enzyme-reaction', 'gene-regulation', 'neural-spike', 'ecological-growth', 'predator-prey', 'population-diffusion', 'immune-recognition'],
  },
  {
    id: 'topology-spatial-relations',
    title: 'Topology Spatial Relations',
    branches: ['connected-components', 'neighborhood-system', 'closure-boundary', 'homeomorphism', 'covering-space', 'fundamental-group', 'homology', 'torus-structure', 'knot-relation', 'simplicial-complex'],
  },
  {
    id: 'graph-networks',
    title: 'Graph Networks',
    branches: ['node-degree', 'shortest-path', 'connected-components', 'community-detection', 'network-flow', 'matching-cover', 'graph-laplacian', 'spectral-clustering', 'directed-graph', 'hypergraph'],
  },
  {
    id: 'image-vision',
    title: 'Image Vision',
    branches: ['pixel-coordinate', 'edge-detection', 'convolution-kernel', 'texture-pattern', 'color-space', 'histogram', 'morphology', 'feature-points', 'optical-flow', 'perspective-projection'],
  },
  {
    id: 'information-encoding',
    title: 'Information Encoding',
    branches: ['binary-encoding', 'gray-code', 'checksum', 'crc', 'hash-mapping', 'substitution-cipher', 'permutation-cipher', 'error-correcting-code', 'entropy-coding', 'commitment-hash'],
  },
  {
    id: 'music-sound-signal',
    title: 'Music Sound Signal',
    branches: ['beat-period', 'pitch-mapping', 'chord-structure', 'melody-sequence', 'spectrum-transform', 'filter-bank', 'envelope-curve', 'reverb-delay', 'phase-difference', 'sampling-quantization'],
  },
  {
    id: 'language-symbols',
    title: 'Language Symbols',
    branches: ['character-mapping', 'lexical-rule', 'syntax-tree', 'context-free-grammar', 'semantic-role', 'symbol-substitution', 'morphology', 'dependency-parse', 'logical-predicate', 'type-system'],
  },
  {
    id: 'state-memory-dynamics',
    title: 'State Memory Dynamics',
    branches: ['click-memory', 'history-window', 'state-machine', 'time-decay', 'half-life', 'queue-cache', 'event-sequence', 'feedback-system', 'markov-state', 'chain-history'],
  },
  {
    id: 'engineering-mechanics-circuits',
    title: 'Engineering Mechanics Circuits',
    branches: ['mechanical-transmission', 'gear-system', 'linkage', 'control-system', 'feedback-loop', 'circuit-network', 'filter', 'logic-gate-array', 'sensor-calibration', 'robot-motion'],
  },
  {
    id: 'composite-systems',
    title: 'Composite Systems',
    branches: ['multi-structure-boss', 'cross-domain-composition', 'formula-splicing', 'hybrid-gating', 'multi-stage-verification', 'nested-structure', 'structure-switching', 'random-structure-pack', 'adversarial-structure', 'long-horizon-composition'],
  },
];

const FAMILIES = [
  ['affine_calibration', 'affine calibration', 2, 5, 'u=(a*x+b*y+c) mod N; v=(d*x+e*y+f) mod N'],
  ['matrix_projection', 'matrix projection', 3, 6, 'B=M*A+bias mod N'],
  ['residue_ring_lock', 'residue ring lock', 3, 7, 'B=A+residue_bucket(A) mod N'],
  ['piecewise_threshold_gate', 'piecewise threshold gate', 4, 8, 'B=if(score(A)>threshold, formulaA, formulaB)'],
  ['lookup_permutation_table', 'lookup permutation table', 4, 8, 'B=A+table(index(A)) mod N'],
  ['prime_crt_key', 'prime CRT key', 6, 10, 'B=CRT(local residues)+bias mod N'],
  ['graph_path_flow', 'graph path flow', 5, 9, 'B=A+path_distance(A,target) mod N'],
  ['board_rule_region', 'board rule region', 5, 9, 'B=branch(board_rule(A))'],
  ['state_memory_window', 'state memory window', 6, 10, 'B=A+memory_window(context) mod N'],
  ['finite_state_machine', 'finite state machine', 6, 10, 'B=state_transition(A,state) mod N'],
  ['time_decay_half_life', 'time decay half-life', 6, 10, 'B=A+floor(A0/2^bucket(time)) mod N'],
  ['recurrence_sequence', 'recurrence sequence', 5, 9, 'B=A+sequence(index(A)) mod N'],
  ['probability_seed_kernel', 'probability seed kernel', 5, 9, 'B=A+seeded_probability_bucket(A) mod N'],
  ['entropy_information_bucket', 'entropy information bucket', 6, 10, 'B=A+bucket(entropy(A)) mod N'],
  ['optimization_objective', 'optimization objective', 5, 10, 'B=branch(argmin(cost_i(A)))'],
  ['game_payoff_strategy', 'game payoff strategy', 5, 10, 'B=branch(payoff(A)>=threshold)'],
  ['wave_periodic_phase', 'wave periodic phase', 4, 9, 'B=A+periodic_phase(A) mod N'],
  ['spectral_fourier_filter', 'spectral Fourier filter', 6, 10, 'B=A+harmonic_filter(A) mod N'],
  ['convolution_local_kernel', 'convolution local kernel', 5, 9, 'B=A+local_kernel(A) mod N'],
  ['bio_growth_reaction', 'biological growth reaction', 5, 9, 'B=A+reaction_growth(A) mod N'],
  ['chemical_balance_network', 'chemical balance network', 5, 9, 'B=A+reaction_balance(A) mod N'],
  ['language_symbol_grammar', 'language symbol grammar', 5, 9, 'B=A+symbol_parse_bucket(A) mod N'],
  ['group_orbit_symmetry', 'group orbit symmetry', 6, 10, 'B=group_action(g,A)+bias mod N'],
  ['complex_mobius_map', 'complex Mobius map', 7, 10, 'B=Mobius(A)+bias mod N'],
  ['tensor_curvature_field', 'tensor curvature field', 8, 10, 'B=A+contract(curvature_tensor(A)) mod N'],
  ['chain_state_commitment', 'chain state commitment', 7, 10, 'B=A+hash_state_bucket(chain) mod N'],
  ['special_constant_field', 'special constant field', 5, 9, 'B=A+bucket(pi,e,phi,A) mod N'],
  ['composite_boss_pack', 'composite boss pack', 8, 10, 'B=combine(formula_1,...,formula_k) mod N'],
];

function titleCase(value) {
  return value
    .split('-')
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');
}

function writeDomain(domain) {
  const dir = path.join(OUT_ROOT, domain.id);
  fs.mkdirSync(dir, { recursive: true });

  domain.branches.forEach((branch, index) => {
    const rows = FAMILIES.map(([id, label, min, max, prototype]) => {
      const familyId = `${domain.id.replace(/-/g, '.')}.${branch}.${id}`;
      const boss = max >= 9 ? 'yes' : 'component';
      return `| ${familyId} | ${label} | ${min}-${max} | ${titleCase(branch)} | ${boss} | \`${prototype}\` |`;
    });

    const body = [
      `# ${domain.title} Extension ${String(index + 1).padStart(2, '0')} ${titleCase(branch)}`,
      '',
      '## Purpose',
      '',
      `This file defines executable formula families for the ${domain.title} domain library.`,
      '',
      '## Formula Families',
      '',
      '| Family ID | Subclass | Difficulty | Theme Scope | Boss | Prototype |',
      '|---|---|---|---|---|---|',
      ...rows,
      '',
      '## Integration Rule',
      '',
      'Each row is intended to be materialized into a directly allocatable, executable, and verifiable formula asset.',
      '',
    ].join('\n');

    fs.writeFileSync(path.join(dir, `${String(index + 1).padStart(2, '0')}_${branch}.md`), body, 'utf8');
  });

  const index = [
    `# ${domain.title} Extension Formula Library`,
    '',
    `Branches: ${domain.branches.length}`,
    `Formula families per branch: ${FAMILIES.length}`,
    `Total candidate families: ${domain.branches.length * FAMILIES.length}`,
    '',
    '| No. | Branch | File |',
    '|---:|---|---|',
    ...domain.branches.map((branch, i) => `| ${i + 1} | ${titleCase(branch)} | ${String(i + 1).padStart(2, '0')}_${branch}.md |`),
    '',
  ].join('\n');

  fs.writeFileSync(path.join(dir, 'README.md'), index, 'utf8');
}

function main() {
  fs.mkdirSync(OUT_ROOT, { recursive: true });
  DOMAINS.forEach(writeDomain);
  console.log(JSON.stringify({ output: OUT_ROOT, domains: DOMAINS.length, families: FAMILIES.length }, null, 2));
}

main();
