#!/usr/bin/env node
import fs from 'fs';
import os from 'os';
import path from 'path';

import { DOCCENTER_API_URL } from '../src/data/doc-paths.js';

const ROOT = '/Users/ivx/Documents/VLCode-Lite';
const SPEC_PATH = path.join(ROOT, 'docs', 'vl-workflow-spec-3.19.md');
const AUTH_PATH = path.join(os.homedir(), '.vl-code', 'auth.json');
const APPLY = process.argv.includes('--apply');

const cookie = process.env.DOCCENTER_COOKIE || (() => {
  try {
    return JSON.parse(fs.readFileSync(AUTH_PATH, 'utf-8')).cookie;
  } catch {
    return '';
  }
})();

if (!cookie) {
  console.error('Missing DocCenter cookie. Set DOCCENTER_COOKIE or login so ~/.vl-code/auth.json exists.');
  process.exit(1);
}

const headers = {
  'Content-Type': 'application/json',
  Cookie: String(cookie).startsWith('ih5bearer=') ? String(cookie) : `ih5bearer=${cookie}`,
};

async function dcPost(endpoint, body) {
  const res = await fetch(`${DOCCENTER_API_URL}/${endpoint}`, {
    method: 'POST',
    headers,
    body: JSON.stringify(body),
  });
  const text = await res.text();
  try {
    return JSON.parse(text);
  } catch {
    throw new Error(`DocCenter returned non-JSON for ${endpoint}: ${text.slice(0, 300)}`);
  }
}

async function loadDocByPath(docPath) {
  const list = await dcPost('SERVICE_DocCenter_GetDocList', {
    keyword: 'Workflow Spec',
    tagId: 0,
    page: 1,
    pageSize: 100,
  });
  return (list?.data || []).find(doc => String(doc.path) === String(docPath)) || null;
}

async function main() {
  const currentContent = fs.readFileSync(SPEC_PATH, 'utf-8');
  const existing = await loadDocByPath(3);

  if (!existing) {
    throw new Error('DocCenter Path 3 was not found');
  }

  const docId = existing._id || existing.id;
  const remote = await dcPost('SERVICE_DocCenter_GetDocById', { docId });
  const remoteContent = remote?.data?.currentContent || '';

  if (remoteContent === currentContent) {
    console.log(`unchanged path 3  VL Workflow Spec 3.19  (docId ${docId})`);
    return;
  }

  if (!APPLY) {
    console.log(`publish path 3  VL Workflow Spec 3.19  (docId ${docId})`);
    return;
  }

  const result = await dcPost('SERVICE_DocCenter_SaveAsVersion', {
    path: '3',
    name: 'VL Workflow Spec 3.19',
    description: 'Canonical workflow specification with Doc ID resolution priority, Tool_* extension profiles, tool events, clientRunToken, and checkpoint rerun semantics.',
    currentContent,
    changeNote: 'v3.19 — clarify persisted Doc ID bindings, path slot aliases, and runtime DocCenter resolution priority',
  });

  console.log(JSON.stringify({
    success: result?.success ?? null,
    message: result?.message ?? null,
    data: result?.data ?? null,
  }, null, 2));
}

main().catch(err => {
  console.error(err.message);
  process.exit(1);
});
