#!/usr/bin/env node
/**
 * Rewrites the `provider` of the datasource block in prisma/schema.prisma to match
 * DATABASE_PROVIDER, then leaves the rest of the schema untouched.
 *
 * Prisma requires the provider to be a literal (env() is not allowed there), but the
 * NABDH schema deliberately uses only portable scalars, so the same models run on both
 * engines. Local demos default to SQLite (zero setup); Docker/production use PostgreSQL.
 *
 * Idempotent: running it twice is a no-op.
 */
import { readFileSync, writeFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'

const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
const SCHEMA = join(ROOT, 'prisma', 'schema.prisma')
const SUPPORTED = new Set(['sqlite', 'postgresql'])

function readEnvFile(name) {
  try {
    return readFileSync(join(ROOT, name), 'utf8')
  } catch {
    return ''
  }
}

/** Minimal .env reader — we only need it before Next.js has loaded anything. */
function envValue(key) {
  if (process.env[key]) return process.env[key]
  for (const file of ['.env.local', '.env']) {
    const match = readEnvFile(file).match(new RegExp(`^\\s*${key}\\s*=\\s*(.*)$`, 'm'))
    if (match) return match[1].trim().replace(/^["']|["']$/g, '')
  }
  return undefined
}

const provider = (envValue('DATABASE_PROVIDER') || 'sqlite').toLowerCase()

if (!SUPPORTED.has(provider)) {
  console.error(
    `[db-prepare] Unsupported DATABASE_PROVIDER "${provider}". Use one of: ${[...SUPPORTED].join(', ')}`,
  )
  process.exit(1)
}

const original = readFileSync(SCHEMA, 'utf8')
const datasourceRe = /(datasource\s+db\s*\{[^}]*?provider\s*=\s*")([a-z]+)(")/s
const match = original.match(datasourceRe)

if (!match) {
  console.error('[db-prepare] Could not locate the datasource provider in prisma/schema.prisma')
  process.exit(1)
}

if (match[2] === provider) {
  console.log(`[db-prepare] provider already "${provider}" — nothing to do`)
  process.exit(0)
}

writeFileSync(SCHEMA, original.replace(datasourceRe, `$1${provider}$3`), 'utf8')
console.log(`[db-prepare] datasource provider: "${match[2]}" -> "${provider}"`)
