import { createSignal } from "solid-js"
import { getLogger } from "../lib/logger"

const log = getLogger("solo")

export interface SoloState {
  isAutonomous: boolean
  autoApproval: boolean
  isApex: boolean // New APEX Mode state
  maxSteps: number
  currentStep: number
  activeTaskId: string | null
  taskQueue: string[]
}

const [soloStates, setSoloStates] = createSignal<Map<string, SoloState>>(new Map())

export function getSoloState(instanceId: string): SoloState {
  const state = soloStates().get(instanceId)
  if (!state) {
    return {
      isAutonomous: false,
      autoApproval: false,
      isApex: false,
      maxSteps: 50,
      currentStep: 0,
      activeTaskId: null,
      taskQueue: [],
    }
  }
  return state
}

export function toggleApex(instanceId: string) {
  const current = getSoloState(instanceId)
  setSoloState(instanceId, { isApex: !current.isApex })
  log.info("APEX Mode toggled", { instanceId, isApex: !current.isApex })
}

export function setSoloState(instanceId: string, partial: Partial<SoloState>) {
  setSoloStates((prev) => {
    const next = new Map(prev)
    const current = getSoloState(instanceId)
    next.set(instanceId, { ...current, ...partial })
    return next
  })
}

export function toggleAutonomous(instanceId: string) {
  const current = getSoloState(instanceId)
  setSoloState(instanceId, { isAutonomous: !current.isAutonomous })
  log.info(`Autonomous mode ${!current.isAutonomous ? "enabled" : "disabled"} for ${instanceId}`)
}

export function toggleAutoApproval(instanceId: string) {
  const current = getSoloState(instanceId)
  setSoloState(instanceId, { autoApproval: !current.autoApproval })
  log.info(`Auto-approval ${!current.autoApproval ? "enabled" : "disabled"} for ${instanceId}`)
}

export function incrementStep(instanceId: string) {
  const state = getSoloState(instanceId)
  setSoloState(instanceId, { currentStep: state.currentStep + 1 })
}

export function resetSteps(instanceId: string) {
  setSoloState(instanceId, { currentStep: 0 })
}

export function setActiveTaskId(instanceId: string, taskId: string | null) {
  setSoloState(instanceId, { activeTaskId: taskId })
}

export function addToTaskQueue(instanceId: string, taskId: string) {
  const current = getSoloState(instanceId)
  setSoloState(instanceId, { taskQueue: [...current.taskQueue, taskId] })
}

export function popFromTaskQueue(instanceId: string): string | null {
  const current = getSoloState(instanceId)
  if (current.taskQueue.length === 0) return null
  const [next, ...rest] = current.taskQueue
  setSoloState(instanceId, { taskQueue: rest })
  return next
}
