import fs from 'fs';
import path from 'path';

const jsonl =
  'C:/Users/한맥/.cursor/projects/d-EENE-Dashboard-0608/agent-transcripts/a31af370-8cc7-4941-8299-96fbb85f1ad8/a31af370-8cc7-4941-8299-96fbb85f1ad8.jsonl';
const root = 'd:/EENE_Dashboard_0608';

const files = new Map();
const replaces = [];

for (const line of fs.readFileSync(jsonl, 'utf8').split('\n')) {
  if (!line.trim()) continue;
  try {
    const o = JSON.parse(line);
    for (const p of o.message?.content ?? []) {
      if (p.type !== 'tool_use') continue;
      const inp = p.input ?? {};
      const fp = inp.path;
      if (!fp?.includes('EENE_Dashboard_0608')) continue;
      if (inp.contents) files.set(fp, inp.contents);
      if (inp.old_string && inp.new_string && fp.includes('frontend')) {
        replaces.push({ fp, old: inp.old_string, new: inp.new_string });
      }
    }
  } catch {
    /* skip */
  }
}

function toRel(fp) {
  return fp
    .replace(/\\/g, '/')
    .replace(/^d:\/EENE_Dashboard_0608\//i, '')
    .replace(/^D:\/EENE_Dashboard_0608\//, '');
}

for (const [fp, initial] of files) {
  let content = initial;
  for (const r of replaces) {
    if (r.fp !== fp) continue;
    if (content.includes(r.old)) content = content.replace(r.old, r.new);
  }
  const rel = toRel(fp);
  if (!rel.startsWith('frontend/') && !rel.startsWith('backend/')) continue;
  const out = path.join(root, rel);
  fs.mkdirSync(path.dirname(out), { recursive: true });
  fs.writeFileSync(out, content, 'utf8');
  console.log('restored', rel, content.length);
}
