#!/usr/bin/env node
// One-shot: ensure a "Reports" project exists, then register the Hermes audit
// HTML as an artifact inside it. Safe to re-run — the project create is guarded
// and the artifact write is content-addressed by timestamp.

import fs from 'node:fs';
import path from 'node:path';
import { ROOT } from '../lib/paths.js';
import { createProject, getProject } from '../lib/projects.js';
import { createArtifact } from '../lib/runtime.js';
import { resetDbHandle } from '../lib/db.js';

const SLUG = 'reports';
const NAME = 'Reports';
const HTML_SOURCE = path.join(ROOT, 'workspace', 'reports', 'hermes-autonomy-audit.html');
const TITLE = 'Hermes Autonomy Audit — How Hermes gets to done, and what we should steal';

function ensureReportsProject() {
  const existing = getProject(SLUG);
  if (existing) return existing;
  return createProject({
    name: NAME,
    slug: SLUG,
    color: '#c8472b',
    description: 'Research audits, design reviews, and shipped reports. First entry: Hermes autonomy audit.',
  });
}

async function main() {
  if (!fs.existsSync(HTML_SOURCE)) {
    throw new Error(`Audit HTML not found at ${HTML_SOURCE}`);
  }
  const project = ensureReportsProject();
  console.log(`[reports] project: ${project.id} (${project.slug})`);

  const content = fs.readFileSync(HTML_SOURCE, 'utf8');
  const result = createArtifact({
    title: TITLE,
    kind: 'html',
    content,
    project_id: project.id,
  });

  console.log(`[reports] artifact: ${result.artifact_id}`);
  console.log(`[reports] file:     ${result.file_path}`);
  console.log(`[reports] open:     http://127.0.0.1:8787/projects/${project.slug}`);
}

main()
  .catch(error => {
    console.error('[reports] failed:', error.message);
    process.exitCode = 1;
  })
  .finally(() => resetDbHandle());
