const fs = require('fs');

let content = fs.readFileSync('sysdoc.js', 'utf8');

content = content.replace(
  "const { extractDeep } = require('./extract-deep.js');",
  "const { extractDeep } = require('./extract-deep.js');\nconst { profileRepo, ARCHETYPES } = require('./repo-profiler.js');\nconst { extractDynamic } = require('./extract-dynamic.js');"
);

content = content.replace(
  /const patterns = extractAllPatterns\(srcRoot\);\s*const deepData = extractDeep\(srcRoot\);/,
  `let patterns = {
    layers: [],
    appsets: [],
    regions: { aws: [], gcp: [], azure: [] },
    cidrs: [],
    naming: [],
    techStack: { containerImages: [] },
    syncWaves: []
  };
  let deepData = { addons: [], scriptParams: [], tfConfigs: [], helmValues: [], stateServices: [] };
  let archetypeStr = ARCHETYPES ? ARCHETYPES.UNKNOWN : 'Unknown';

  if (opts.legacyMode) {
    patterns = extractAllPatterns(srcRoot);
    deepData = extractDeep(srcRoot);
    if (!archetypeStr || archetypeStr === 'Unknown') archetypeStr = 'Infrastructure';
  } else {
    const profile = profileRepo(srcRoot, graph);
    archetypeStr = profile.archetype;
    console.log(\`Detected Repo Archetype: \${archetypeStr} (confidence: \${profile.confidence})\`);
    
    const dynamicData = extractDynamic(graph, archetypeStr, srcRoot);
    deepData = {
      addons: [],
      scriptParams: [],
      tfConfigs: [],
      helmValues: [],
      stateServices: dynamicData.stateServices || [],
      configs: dynamicData.configs || [],
      deploymentPatterns: dynamicData.deploymentPatterns || [],
      networkTopology: dynamicData.networkTopology || []
    };
  }`
);

content = content.replace(
  /await proseMod\.synthesizeReferencePages\(agentKB, deepData, outDir, \{ confluenceCtx, model: process\.env\.LLM_MODEL \|\| 'claude-haiku-4\.5' \}\);/,
  "await proseMod.synthesizeReferencePages(agentKB, deepData, outDir, archetypeStr, { confluenceCtx, model: process.env.LLM_MODEL || 'claude-haiku-4.5' });"
);

fs.writeFileSync('sysdoc.js', content);
