import { NextRequest, NextResponse } from 'next/server'
import { spawn } from 'node:child_process'
import { existsSync, mkdirSync, writeFileSync, readFileSync, createWriteStream } from 'node:fs'
import path from 'node:path'

const REPO_ROOT  = path.resolve(process.cwd(), '..')
const LOGS_DIR   = path.join(REPO_ROOT, 'data', 'logs')
const STATUS_FILE = path.join(LOGS_DIR, 'etl-status.json')

const PYTHON = process.platform === 'win32'
  ? path.join(REPO_ROOT, '.venv', 'Scripts', 'python.exe')
  : path.join(REPO_ROOT, '.venv', 'bin', 'python')

function currentMesAno() {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
}

function pidRunning(pid: number): boolean {
  try { process.kill(pid, 0); return true } catch { return false }
}

function readStatus() {
  if (!existsSync(STATUS_FILE)) return null
  try { return JSON.parse(readFileSync(STATUS_FILE, 'utf8')) } catch { return null }
}

export async function POST(req: NextRequest) {
  const body    = await req.json().catch(() => ({}))
  const mes_ano = (body.mes_ano as string) || currentMesAno()

  // Verifica se já está rodando
  const prev = readStatus()
  if (prev?.running && prev.pid && pidRunning(Number(prev.pid))) {
    return NextResponse.json(
      { error: 'ETL já em execução', mes_ano: prev.mes_ano, started_at: prev.started_at },
      { status: 409 },
    )
  }

  mkdirSync(LOGS_DIR, { recursive: true })
  const logFile = path.join(LOGS_DIR, `etl-${mes_ano}.log`)

  // Cabecalho no log
  const header = `\n${'='.repeat(60)}\nIniciado em: ${new Date().toISOString()}\nComando: python run_monthly.py ${mes_ano}\n${'='.repeat(60)}\n`
  writeFileSync(logFile, header, { flag: 'a' })

  const logStream = createWriteStream(logFile, { flags: 'a' })

  const child = spawn(PYTHON, [path.join(REPO_ROOT, 'run_monthly.py'), mes_ano], {
    cwd:         REPO_ROOT,
    detached:    true,
    windowsHide: true,
    stdio:       ['ignore', 'pipe', 'pipe'],
  })

  child.stdout?.pipe(logStream)
  child.stderr?.pipe(logStream)

  const started_at = new Date().toISOString()
  const status = {
    running:     true,
    pid:         child.pid,
    mes_ano,
    started_at,
    log_file:    logFile,
    exit_code:   null as number | null,
    finished_at: null as string | null,
  }
  writeFileSync(STATUS_FILE, JSON.stringify(status))

  child.on('exit', code => {
    const s = readStatus() ?? status
    s.running     = false
    s.exit_code   = code
    s.finished_at = new Date().toISOString()
    writeFileSync(STATUS_FILE, JSON.stringify(s))
    writeFileSync(logFile, `\n[portal] Processo encerrado com código ${code} em ${s.finished_at}\n`, { flag: 'a' })
  })

  child.unref()

  return NextResponse.json({ ok: true, mes_ano, started_at, pid: child.pid })
}
