'use strict';

/**
 * Publish "Monitoring Oracle Without the Diagnostics Pack".
 *
 * Source: data/oracle-docs/monitoring-without-diagnostics-pack.html
 * Route:  db/blog.js createPost() — the Oracle-dialect idempotent MERGE, the same
 *         path scripts/publish-awr-ash-post.js uses. scripts/seed-blog.js is
 *         pre-cutover and Postgres-only; it cannot reach the live database.
 *
 * This is a NEW post rather than a stub repair, so it is not wired into the
 * ensureColumns() self-heal — that loop only rewrites bodies that still match
 * /\[paste/, and creating posts on every boot is not something a startup path
 * should be doing.
 *
 *     node scripts/publish-diagnostics-pack-post.js          # dry run
 *     node scripts/publish-diagnostics-pack-post.js --write  # publish
 *
 * Idempotent: MERGE on slug, so re-running updates rather than duplicating.
 */

const fs = require('fs');
const path = require('path');
const { htmlToMarkdown } = require('../lib/html-to-markdown');

const SLUG = 'monitoring-oracle-without-diagnostics-pack';
const SRC = path.join(__dirname, '..', 'data', 'oracle-docs',
                      'monitoring-without-diagnostics-pack.html');

const TITLE = 'Monitoring Oracle Without the Diagnostics Pack';
const EXCERPT =
  'What the Oracle Diagnostics Pack actually gates, what stays free, and how to '
  + 'build usable performance history from views that carry no licence — including '
  + 'why V$ACTIVE_SESSION_HISTORY is licensed despite being a V$ view, and why '
  + 'Statspack can only ever live in the database it monitors.';

(async () => {
  const write = process.argv.includes('--write');

  if (!fs.existsSync(SRC)) {
    console.error('FATAL: source not found at ' + SRC);
    process.exit(2);
  }
  const content = htmlToMarkdown(fs.readFileSync(SRC, 'utf8')).trim();

  // Same guards as the AWR repair: never publish a stub, never publish something
  // too short to be the article.
  if (/\[paste\b/i.test(content) || /coming soon/i.test(content)) {
    console.error('FATAL: content contains placeholder text. Aborting.');
    process.exit(2);
  }
  const words = content.split(/\s+/).filter(Boolean).length;
  if (words < 800) {
    console.error('FATAL: only ' + words + ' words — expected ~1600. Aborting.');
    process.exit(2);
  }
  // This article names no product. If that changes, it belongs in the review, not
  // in a silent publish — the blog is Oracle subject matter, not TuneVault news.
  const mentions = (content.match(/tunevault/gi) || []).length;

  console.log('slug          : ' + SLUG);
  console.log('words         : ' + words);
  console.log('sections      : ' + (content.match(/^## /gm) || []).length);
  console.log('code blocks   : ' + (content.match(/^```/gm) || []).length / 2);
  console.log('product refs  : ' + mentions + (mentions ? '  <-- review before publishing' : ''));
  console.log('');

  if (!write) {
    console.log('DRY RUN — nothing written. Re-run with --write to publish.');
    console.log('--- first 300 chars ---');
    console.log(content.slice(0, 300));
    return;
  }

  const blogDb = require('../db/blog');
  await blogDb.createPost({
    title: TITLE,
    slug: SLUG,
    excerpt: EXCERPT,
    content,
    author: 'Kiran Kumar Ale',
    published_at: new Date().toISOString().slice(0, 10),
    read_time_minutes: Math.max(1, Math.round(words / 200)),
  });
  console.log('Published: https://tunevault.app/blog/' + SLUG);
})().catch((e) => {
  console.error('FAILED:', e.message);
  process.exit(1);
});
