#!/usr/bin/env node
/**
 * sync-library — extract the curated exercise library from a SQLite snapshot
 * and write it to prisma/exercises.seed.json (the canonical library source
 * of truth used by both `prisma/seed.ts` for fresh installs and the
 * `ensureExerciseLibrary.cjs` runtime ensure step for updates on existing
 * installs).
 *
 * Default source: ../start9/0.4/seed/data/app.db
 * Default target: prisma/exercises.seed.json
 *
 * Maintainer release loop:
 *   1. Add new exercises in the running app on your StartOS host.
 *   2. ./start9/0.4/refresh_seed.sh <ssh-target>      # pull a fresh snapshot
 *   3. cd proof-of-work && npm run sync-library      # update the JSON
 *   4. git diff prisma/exercises.seed.json            # eyeball the new rows
 *   5. git add prisma/exercises.seed.json && commit
 *   6. Bump start9/0.4/startos/utils.ts:PACKAGE_VERSION + add a version file
 *   7. make -C start9/0.4 clean x86 && make -C start9/0.4 install
 *
 * Notes:
 *   - All exercises in the JSON ship with isCustom=false on consumption,
 *     regardless of how they were created on the maintainer's host. They are
 *     part of the curated library now, not user-custom.
 *   - Removing an exercise from the JSON does NOT remove it from existing
 *     installs (users may have logged sets against it). The system is
 *     additive only.
 *   - This script never touches the snapshot DB. Read-only.
 */

const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');

const repoRoot = path.resolve(__dirname, '..', '..');
const DEFAULT_DB = path.join(repoRoot, 'start9', '0.4', 'seed', 'data', 'app.db');
const DEFAULT_OUT = path.resolve(__dirname, '..', 'prisma', 'exercises.seed.json');

function arg(name, fallback) {
  const i = process.argv.indexOf(name);
  return i >= 0 ? process.argv[i + 1] : fallback;
}

const dbPath = arg('--db', DEFAULT_DB);
const outPath = arg('--out', DEFAULT_OUT);

if (!fs.existsSync(dbPath)) {
  console.error(`[sync-library] snapshot DB not found at ${dbPath}`);
  console.error('  Run start9/0.4/refresh_seed.sh first, or pass --db <path>.');
  process.exit(2);
}

console.error(`[sync-library] reading from ${dbPath}`);

const sql =
  'SELECT name, description, muscleGroups, type, inputFields, defaultWeightUnit ' +
  'FROM Exercise ORDER BY type, name;';
const raw = execFileSync('sqlite3', ['-cmd', '.mode json', dbPath, sql], {
  encoding: 'utf8',
});
const rows = JSON.parse(raw);

const library = rows.map((r) => ({
  name: r.name,
  description: r.description ?? null,
  type: r.type,
  muscleGroups: r.muscleGroups ? JSON.parse(r.muscleGroups) : [],
  inputFields: r.inputFields ? JSON.parse(r.inputFields) : ['sets', 'reps', 'weight'],
  defaultWeightUnit: r.defaultWeightUnit ?? null,
}));

fs.writeFileSync(outPath, JSON.stringify(library, null, 2) + '\n');
console.error(`[sync-library] wrote ${library.length} exercises to ${outPath}`);
