import path from 'node:path'
import {
  createBillingStateStore,
  type BillingPlan,
  type BillingRole,
} from '../src/billing-state'

type ParsedArgs = {
  email: string
  plan: BillingPlan
  role: BillingRole
  canDownload: boolean
  accessStatus: string
}

function readArgValue(args: string[], flag: string) {
  const index = args.indexOf(flag)
  if (index === -1) {
    return ''
  }

  return String(args[index + 1] || '').trim()
}

function readBooleanArg(rawValue: string, fallback: boolean) {
  const value = rawValue.trim().toLowerCase()
  if (!value) {
    return fallback
  }
  if (value === '1' || value === 'true' || value === 'yes' || value === 'on') {
    return true
  }
  if (value === '0' || value === 'false' || value === 'no' || value === 'off') {
    return false
  }
  throw new Error(`Invalid boolean value '${rawValue}'. Use true/false.`)
}

function normalizePlan(value: string): BillingPlan {
  const plan = value.trim().toLowerCase()
  if (plan === 'free' || plan === 'operator' || plan === 'studio' || plan === 'enterprise') {
    return plan
  }
  if (plan === 'explorer') {
    return 'free'
  }
  throw new Error(`Unsupported plan '${value}'.`)
}

function normalizeRole(value: string): BillingRole {
  const role = value.trim().toLowerCase()
  if (role === 'viewer' || role === 'operator' || role === 'reviewer' || role === 'admin') {
    return role
  }
  throw new Error(`Unsupported role '${value}'.`)
}

function parseArgs(argv: string[]): ParsedArgs {
  const email = readArgValue(argv, '--email').toLowerCase()
  if (!email) {
    throw new Error('Provide --email user@example.com')
  }

  const plan = normalizePlan(readArgValue(argv, '--plan') || 'enterprise')
  const role = normalizeRole(readArgValue(argv, '--role') || 'admin')
  const canDownload = readBooleanArg(readArgValue(argv, '--can-download'), plan !== 'free')
  const accessStatus = readArgValue(argv, '--access-status') || (canDownload ? 'active' : 'manual-review')

  return {
    email,
    plan,
    role,
    canDownload,
    accessStatus,
  }
}

function resolveBillingStatePath() {
  return process.env.BILLING_STATE_PATH
    || path.join(process.cwd(), 'data', 'hypertwist-billing-state.json')
}

function main() {
  const parsed = parseArgs(process.argv.slice(2))
  const statePath = resolveBillingStatePath()
  const store = createBillingStateStore({
    statePath,
    defaultPlan: 'free',
    defaultRole: 'operator',
  })

  const entitlement = store.setManualEntitlement({
    email: parsed.email,
    plan: parsed.plan,
    role: parsed.role,
    canDownload: parsed.canDownload,
    accessStatus: parsed.accessStatus,
  })

  console.log(JSON.stringify({
    statePath,
    entitlement,
  }, null, 2))
}

main()
