import { config } from 'dotenv'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'

const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..')

export function cfg() {
  config({ path: resolve(ROOT, '.env'),       override: true })
  config({ path: resolve(ROOT, '.env.local'), override: true })
  return {
    PORT:          process.env.PORT          || 3000,
    ADSB_URL:      process.env.ADSB_URL      || '',
    INFLUX_URL:    process.env.INFLUX_URL    || 'http://localhost:8086',
    INFLUX_TOKEN:  process.env.INFLUX_TOKEN  || '',
    INFLUX_ORG:    process.env.INFLUX_ORG    || 'weather',
    INFLUX_BUCKET: process.env.INFLUX_BUCKET || 'station',
    LATITUDE:      parseFloat(process.env.LATITUDE  || '0'),
    LONGITUDE:     parseFloat(process.env.LONGITUDE || '0'),
    ALTITUDE:      parseFloat(process.env.ALTITUDE  || '0'),
    TZ:            process.env.TZ || 'UTC',
  }
}

// Returns the UTC offset in minutes for the configured TZ at a given date
export function tzOffsetMinutes(date = new Date()) {
  const tz = cfg().TZ
  // Format the date in the target timezone and compare to UTC
  const local = new Date(date.toLocaleString('en-US', { timeZone: tz }))
  const utc   = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }))
  return Math.round((local - utc) / 60_000)
}

// Shift a UTC date to local-time-as-if-UTC (for day bucketing)
export function toLocalMidnight(date = new Date()) {
  const offset = tzOffsetMinutes(date)
  const local  = new Date(date.getTime() + offset * 60_000)
  local.setUTCHours(0, 0, 0, 0)
  return local
}

// Get YYYY-MM-DD string in local timezone
export function localDateStr(date = new Date()) {
  const offset  = tzOffsetMinutes(date)
  const shifted = new Date(date.getTime() + offset * 60_000)
  return shifted.toISOString().slice(0, 10)
}
