#!/usr/bin/env node
/**
 * DB에 저장된 회의록 generated_minutes에 prepareMeetingMinutesForApi(말미 제거·제목 승격)를
 * 일괄 적용합니다. 서버 재시작 없이 기존 데이터를 정리할 때 사용합니다.
 *
 * 사용: node scripts/normalize-stored-meeting-minutes.js
 * 요구: .env에 DB_HOST, DB_DATABASE, DB_USERNAME, DB_PASSWORD 등 (apply-schema와 동일)
 */
require("dotenv").config({ quiet: true });

const { Pool } = require("pg");
const path = require("path");

const { prepareMeetingMinutesForApi } = require(path.join(__dirname, "..", "lib", "meeting-minutes"));
const { extractMeetingSummary } = require(path.join(__dirname, "..", "lib", "meeting-minutes-summary"));

const getConfig = () => ({
  host: process.env.DB_HOST,
  port: Number(process.env.DB_PORT || 5432),
  database: process.env.DB_DATABASE,
  user: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  ssl: process.env.DB_SSL === "1" ? { rejectUnauthorized: false } : false,
});

const validateConfig = (config) => {
  const missing = ["host", "database", "user", "password"].filter((key) => !config[key]);
  if (missing.length) {
    throw new Error(`Missing PostgreSQL envs: ${missing.join(", ")}`);
  }
};

async function main() {
  const config = getConfig();
  validateConfig(config);
  const pool = new Pool(config);
  let updated = 0;
  let unchanged = 0;
  try {
    const r = await pool.query(
      `SELECT id, user_email, generated_minutes FROM meeting_ai_meetings ORDER BY created_at ASC`
    );
    for (const row of r.rows) {
      const raw = row.generated_minutes != null ? String(row.generated_minutes) : "";
      const next = prepareMeetingMinutesForApi(raw);
      if (next === raw) {
        unchanged++;
        continue;
      }
      const summaryText = extractMeetingSummary(next, 1200);
      await pool.query(
        `UPDATE meeting_ai_meetings
         SET generated_minutes = $1, summary_text = $2, updated_at = NOW()
         WHERE id = $3::uuid AND user_email = $4`,
        [next, summaryText || null, row.id, row.user_email]
      );
      updated++;
      console.log("updated:", row.id, row.user_email);
    }
    console.log(`Done. updated=${updated}, unchanged=${unchanged}, total=${r.rows.length}`);
  } finally {
    await pool.end();
  }
}

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