#!/usr/bin/env node
/** Cron-safe historical Synchron importer.
 *
 * Reads one Synchron order per request (per_page=1). Reuses
 * import-month-order.mjs for every write, then
 * verifies Supabase and confirms the Workspace sync API accepted the trip.
 * Dry-run by default. The JSONL log contains IDs, counts and issue codes only.
 */
import { spawnSync } from 'node:child_process'
import { appendFileSync, existsSync, mkdirSync, openSync, closeSync, readFileSync, unlinkSync } from 'node:fs'
import { basename, resolve } from 'node:path'
import { createClient } from '@supabase/supabase-js'
import { verifyImportedTrip } from './lib/verify-import.mjs'

const ORDER_SCRIPT = resolve('scripts/synchron/import-month-order.mjs')
const MINUTE = 60_000

function parseArgs(argv) {
  const out = { startPage: 1, endPage: null, apply: false,
    verifyOnly: false, logDir: resolve('logs') }
  for (let i = 0; i < argv.length; i++) {
    const key = argv[i]
    if (key === '--apply') { out.apply = true; continue }
    if (key === '--verify-only') { out.verifyOnly = true; continue }
    if (!['--month', '--start-page', '--end-page', '--workspace-url',
      '--log-dir'].includes(key) || !argv[i + 1] ||
      argv[i + 1].startsWith('--')) throw new Error(`Invalid option: ${key}`)
    const value = argv[++i]
    if (key === '--month') out.month = value
    if (key === '--start-page') out.startPage = Number(value)
    if (key === '--end-page') out.endPage = Number(value)
    if (key === '--workspace-url') out.workspaceUrl = value
    if (key === '--log-dir') out.logDir = resolve(value)
  }
  if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(out.month || '') ||
      !Number.isSafeInteger(out.startPage) || out.startPage < 1 ||
      (out.endPage !== null && (!Number.isSafeInteger(out.endPage) || out.endPage < out.startPage)) ||
      (out.apply && out.verifyOnly)) {
    throw new Error('Use --month YYYY-MM, valid one-order page numbers, and one mode')
  }
  if (out.apply && !out.workspaceUrl) throw new Error('--apply requires --workspace-url')
  return out
}

function loadEnv() {
  return Object.fromEntries(readFileSync('.env', 'utf8').split('\n')
    .filter((line) => line.includes('=') && !line.startsWith('#'))
    .map((line) => { const index = line.indexOf('='); return [line.slice(0, index).trim(),
      line.slice(index + 1).trim().replace(/^['"]|['"]$/g, '')] }))
}

function runOrder(args, timeoutMs) {
  const result = spawnSync(process.execPath, [ORDER_SCRIPT, ...args], {
    cwd: process.cwd(), encoding: 'utf8', timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024,
  })
  const events = (result.stdout || '').split('\n').filter((line) => line.startsWith('{'))
    .flatMap((line) => { try { return [JSON.parse(line)] } catch { return [] } })
  return { ok: result.status === 0 && !result.error, timeout: result.error?.code === 'ETIMEDOUT',
    events, exitCode: result.status }
}

async function ensureWorkspaceSync(options, env, tripId) {
  try {
    const target = new URL(options.workspaceUrl)
    const deployed = env.NEXT_PUBLIC_APP_URL ? new URL(env.NEXT_PUBLIC_APP_URL).origin : null
    if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password ||
        target.pathname !== '/' || target.search || target.hash ||
        !(target.origin === deployed || ['localhost', '127.0.0.1'].includes(target.hostname))) {
      return false
    }
    const response = await fetch(new URL('/api/internal/hha-sync', target), {
      method: 'POST', redirect: 'error',
      headers: { Authorization: `Bearer ${env.CRON_SECRET}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ trip_id: tripId }), signal: AbortSignal.timeout(60_000),
    })
    const body = await response.json().catch(() => ({}))
    return response.ok && body.ok === true && body.total === 1 && body.synced === 1 &&
      Array.isArray(body.failed) && body.failed.length === 0
  } catch { return false }
}

function logWriter(options) {
  mkdirSync(options.logDir, { recursive: true })
  const path = resolve(options.logDir, `synchron-${options.month}-import-verified.jsonl`)
  console.log(`Import log: ${path}`)
  return (event) => {
    const row = { at: new Date().toISOString(), month: options.month, ...event }
    appendFileSync(path, `${JSON.stringify(row)}\n`, { mode: 0o600 })
    console.log(JSON.stringify(row))
  }
}

async function checkTrip(db, info) {
  try {
    return await verifyImportedTrip(db, info)
  } catch {
    return { ok: false, issues: ['verification_unavailable'] }
  }
}

async function recordResult(db, options, env, record, info, importStatus) {
  const checked = await checkTrip(db, info)
  const synced = checked.ok && await ensureWorkspaceSync(options, env, checked.trip_id)
  const status = checked.ok && synced
    ? (importStatus === 'skipped_verified' ? 'skipped_verified' : 'imported_verified')
    : importStatus === 'import_failed' ? 'import_failed' : 'import_incomplete'
  record({ page: info.page, api_current_page: info.api_current_page,
    api_total_pages: info.total_pages,
    ref: info.ref, source_order_id: info.source_order_id,
    status, import_status: importStatus,
    issues: [...checked.issues, ...(checked.ok && !synced ? ['workspace_sync_failed'] : [])],
    counts: checked.counts })
  return checked.ok && synced
}

function baseArgs(options, page, perPage) {
  return ['--month', options.month, '--page', String(page), '--per-page', String(perPage)]
}

async function processSingle(db, options, env, record, page, preflight = null) {
  const dry = preflight || runOrder(baseArgs(options, page, 1), 90_000)
  const empty = dry.events.find((event) => event.mode === 'empty-month')
  if (dry.ok && empty && page === 1 && empty.total_pages === 0) {
    record({ page, api_current_page: 1, api_total_pages: 0, status: 'empty_month' })
    return { ok: true, totalPages: 0 }
  }
  const info = dry.events.find((event) => event.mode === 'dry-run')
  if (!dry.ok || !info) {
    record({ page, status: dry.timeout ? 'preflight_timeout' : 'preflight_failed' })
    return { ok: false, totalPages: null }
  }
  if (info.page !== page || info.api_current_page !== page ||
      !Number.isSafeInteger(info.total_pages) || info.total_pages < page) {
    record({ page, status: 'pagination_contract_failed' })
    return { ok: false, totalPages: null }
  }
  if (!options.apply && !options.verifyOnly) {
    record({ page, api_current_page: info.api_current_page, api_total_pages: info.total_pages,
      ref: info.ref, status: 'dry_run_ready',
      permits: info.permits, ratecons: info.ratecons, existing: info.existing_trip })
    return { ok: true, totalPages: info.total_pages }
  }
  const existing = await checkTrip(db, info)
  if (options.verifyOnly) {
    record({ page, api_current_page: info.api_current_page, api_total_pages: info.total_pages,
      ref: info.ref, status: existing.ok ? 'skipped_verified' : 'missing_or_incomplete',
      issues: existing.issues, counts: existing.counts })
    return { ok: existing.ok, totalPages: info.total_pages }
  }
  if (existing.ok) {
    const synced = await ensureWorkspaceSync(options, env, existing.trip_id)
    record({ page, api_current_page: info.api_current_page, api_total_pages: info.total_pages,
      ref: info.ref, status: synced ? 'skipped_verified' : 'mirror_sync_failed',
      issues: synced ? [] : ['workspace_sync_failed'], counts: existing.counts })
    return { ok: synced, totalPages: info.total_pages }
  }
  const applied = runOrder([...baseArgs(options, page, 1), '--expect-token', info.ref.slice(3),
    '--workspace-url', options.workspaceUrl, '--apply'], 20 * MINUTE)
  const ok = await recordResult(db, options, env, record, info,
    applied.ok ? (info.existing_trip ? 'resumed' : 'imported') : 'import_failed')
  return { ok, totalPages: info.total_pages }
}

async function main() {
  const options = parseArgs(process.argv.slice(2))
  if (!existsSync(ORDER_SCRIPT)) throw new Error('Run this script from the Workspace repository')
  const env = loadEnv()
  if (!env.NEXT_PUBLIC_SUPABASE_URL || !env.SUPABASE_SERVICE_ROLE_KEY ||
      !env.SYNCHRON_API_TOKEN || (options.apply && !env.CRON_SECRET)) {
    throw new Error('Required Workspace environment variables are missing')
  }
  const db = createClient(env.NEXT_PUBLIC_SUPABASE_URL, env.SUPABASE_SERVICE_ROLE_KEY,
    { auth: { persistSession: false } })
  const record = logWriter(options)
  const lockPath = resolve(options.logDir, `synchron-${options.month}-import.lock`)
  let lock
  try {
    lock = openSync(lockPath, 'wx', 0o600)
  } catch {
    throw new Error('Import lock exists; another run may be active. Inspect before removing it')
  }
  let completedPages = 0
  let failedPages = 0
  let totalPages = null
  try {
    for (let page = options.startPage;
      page <= (options.endPage ?? totalPages ?? Number.MAX_SAFE_INTEGER); page++) {
      const result = await processSingle(db, options, env, record, page)
      if (result.totalPages !== null) {
        if (totalPages !== null && result.totalPages !== totalPages) {
          record({ page, status: 'pagination_changed', previous_total: totalPages,
            new_total: result.totalPages })
          failedPages++
          break
        }
        totalPages = result.totalPages
      }
      if (result.ok) completedPages++
      else failedPages++
      if (totalPages === null || page >= totalPages) break
    }
  } finally {
    closeSync(lock)
    unlinkSync(lockPath)
  }
  record({ status: 'run_finished', mode: options.apply ? 'apply' : options.verifyOnly ? 'verify_only' : 'dry_run',
    completed_pages: completedPages, failed_pages: failedPages, total_pages: totalPages })
  if (failedPages) process.exitCode = 1
}

main().catch(() => {
  // Never echo raw errors: providers and database drivers may include URLs or credentials.
  console.error(`Import runner failed (${basename(process.argv[1])}); check configuration and private logs`)
  process.exitCode = 2
})
