import { Permission } from "@/permission"
import { Session } from "@/session/session"
import {
  shouldAskPlanFollowup as _shouldAskPlanFollowup,
  askPlanFollowup as _askPlanFollowup,
  abortPlanFollowup as _abortPlanFollowup,
  recoverDanglingAssistant as _recoverDanglingAssistant,
  recoverProviderFinishError as _recoverProviderFinishError,
  ensurePlanDir as _ensurePlanDir,
  insertPlanReminders as _insertPlanReminders,
  CODE_SWITCH_TEXT as _CODE_SWITCH_TEXT,
  resolveCloseReason as _resolveCloseReason,
  MAX_COMPACTION_ATTEMPTS as _MAX_COMPACTION_ATTEMPTS,
  guardCompactionAttempt as _guardCompactionAttempt,
} from "./prompt-plan"
import {
  type EnvCache as EnvCacheType,
  injectEditorContext as _injectEditorContext,
  createShellDecoders as _createShellDecoders,
  hasCompletedSummary as _hasCompletedSummary,
  trimBeforeLastSummary as _trimBeforeLastSummary,
  stripHistoricalMedia as _stripHistoricalMedia,
  maybeStripHistoricalMedia as _maybeStripHistoricalMedia,
} from "./prompt-context"

const modes = ["ask", "plan"]

export namespace SaeeolSessionPrompt {
  export const shouldAskPlanFollowup = _shouldAskPlanFollowup
  export const askPlanFollowup = _askPlanFollowup
  export const abortPlanFollowup = _abortPlanFollowup

  export const recoverDanglingAssistant = _recoverDanglingAssistant
  export const recoverProviderFinishError = _recoverProviderFinishError

  export const ensurePlanDir = _ensurePlanDir
  export const insertPlanReminders = _insertPlanReminders
  export const CODE_SWITCH_TEXT = _CODE_SWITCH_TEXT

  export const resolveCloseReason = _resolveCloseReason
  export const MAX_COMPACTION_ATTEMPTS = _MAX_COMPACTION_ATTEMPTS
  export const guardCompactionAttempt = _guardCompactionAttempt

  export const hasCompletedSummary = _hasCompletedSummary
  export const trimBeforeLastSummary = _trimBeforeLastSummary

  export const stripHistoricalMedia = _stripHistoricalMedia
  export const maybeStripHistoricalMedia = _maybeStripHistoricalMedia

  export function guardPermissions(input: {
    agent: { name: string; permission: Permission.Ruleset }
    session: Pick<Session.Info, "permission">
  }) {
    const rules = input.session.permission ?? []
    if (!modes.includes(input.agent.name)) return rules
    return Permission.merge(
      rules,
      input.agent.permission,
      rules.filter((rule) => rule.action === "deny"),
    )
  }

  export function hardPermissions(input: { agent: { name: string; permission: Permission.Ruleset } }) {
    if (!modes.includes(input.agent.name)) return
    return input.agent.permission
  }

  export type EnvCache = EnvCacheType
  export const injectEditorContext = _injectEditorContext
  export const createShellDecoders = _createShellDecoders
}
