import { herdrBinary } from '../sync/tools'
import type { AdoptedName, LaneAgent, LaneStatusSource } from './types'

type HerdrAgent = {
  name?: string
  pane_id: string
  agent_status: string
  agent_session?: unknown
  cwd?: unknown
  terminal_title_stripped?: unknown
}

const METADATA_SOURCE = 'pf-plans'
/** The title Claude Code shows until a session has one of its own. */
const UNTITLED_SESSION = 'Claude Code'

const isHerdrAgent = (value: unknown): value is HerdrAgent => {
  if (typeof value !== 'object' || value === null) return false
  const candidate = value as Record<string, unknown>
  return (
    typeof candidate.pane_id === 'string' &&
    typeof candidate.agent_status === 'string' &&
    (candidate.name === undefined || typeof candidate.name === 'string')
  )
}

const sessionOf = ({ agent_session }: HerdrAgent): string | null => {
  if (typeof agent_session !== 'object' || agent_session === null) return null
  const { value } = agent_session as Record<string, unknown>
  return typeof value === 'string' && value !== '' ? value : null
}

/** The session's own title from the terminal title without its status glyph; null for none or the default one. */
const titleOf = ({ terminal_title_stripped }: HerdrAgent): string | null => {
  const title = typeof terminal_title_stripped === 'string' ? terminal_title_stripped.trim() : ''
  return title === '' || title === UNTITLED_SESSION ? null : title
}

const laneAgentOf = (agent: HerdrAgent, name: string): LaneAgent => {
  const title = titleOf(agent)
  return {
    name,
    pane: agent.pane_id,
    status: agent.agent_status,
    session: sessionOf(agent),
    cwd: typeof agent.cwd === 'string' ? agent.cwd : null,
    ...(title ? { title } : {}),
  }
}

/**
 * Reads the JSON of `herdr agent list`; throws on anything else, so a changed format is seen, not guessed.
 * Agents without a name are left out, except the one in `adopt.pane`, which takes `adopt.name`.
 */
export const parseAgentList = (json: string, adopt?: AdoptedName): LaneAgent[] => {
  const agents = (JSON.parse(json) as { result?: { agents?: unknown } }).result?.agents
  if (!Array.isArray(agents) || !agents.every(isHerdrAgent)) throw new Error('herdr agent list: unexpected answer')
  return agents.flatMap((agent) => {
    const name = agent.name || (agent.pane_id === adopt?.pane ? adopt.name : '')
    return name ? [laneAgentOf(agent, name)] : []
  })
}

/**
 * Sets or, with null, clears the sidebar title of a pane. The pane id goes before the options:
 * herdr 0.9.0 rejects it after them, despite `--help`.
 */
export const titleArguments = (pane: string, title: string | null): string[] => [
  'pane',
  'report-metadata',
  pane,
  '--source',
  METADATA_SOURCE,
  ...(title ? ['--title', title] : ['--clear-title']),
]

/** Sets the label of a pane, or with null clears it; the pane id goes before the option, as in `titleArguments`. */
export const renameArguments = (pane: string, label: string | null): string[] => [
  'pane',
  'rename',
  pane,
  label ?? '--clear',
]

/** Runs the herdr CLI with these arguments and returns its stdout; throws when it fails. */
export type HerdrRunner = (args: string[]) => string

/** As `HerdrRunner`, without holding the event loop while herdr answers. */
export type HerdrAsyncRunner = (args: string[]) => Promise<string>

const failureOf = (args: string[], stderr: string, exitCode: number | null): Error =>
  new Error(`herdr ${args.slice(0, 2).join(' ')}: ${stderr.trim() || `exit ${exitCode}`}`)

/**
 * Runs the herdr binary of `herdrBinary` (`HERDR_BIN_PATH`, else `herdr` from the PATH) and returns its stdout;
 * throws with herdr's own error text when it fails or is not running.
 */
export const herdrRunner =
  (env: Record<string, string | undefined>): HerdrRunner =>
  (args) => {
    const result = Bun.spawnSync([herdrBinary(env), ...args], { stdout: 'pipe', stderr: 'pipe', env })
    if (result.exitCode !== 0) throw failureOf(args, result.stderr.toString(), result.exitCode)
    return result.stdout.toString()
  }

/** As `herdrRunner`, but the answer arrives as a promise, so a live view keeps drawing while herdr answers. */
export const herdrRunnerAsync =
  (env: Record<string, string | undefined>): HerdrAsyncRunner =>
  async (args) => {
    const child = Bun.spawn([herdrBinary(env), ...args], { stdout: 'pipe', stderr: 'pipe', env })
    const [stdout, stderr, exitCode] = await Promise.all([
      new Response(child.stdout).text(),
      new Response(child.stderr).text(),
      child.exited,
    ])
    if (exitCode !== 0) throw failureOf(args, stderr, exitCode)
    return stdout
  }

export const runHerdr: HerdrRunner = herdrRunner(process.env)

/** The named agents of `herdr agent list`, read without holding the event loop; rejects as `listAgents` throws. */
export const listHerdrAgents = async (run: HerdrAsyncRunner = herdrRunnerAsync(process.env)): Promise<LaneAgent[]> =>
  parseAgentList(await run(['agent', 'list']))

/** `ownPane` is herdr's id of the pane this process runs in (`HERDR_PANE_ID`), undefined outside herdr. */
export const createHerdrLaneStatusSource = (run: HerdrRunner, ownPane?: string): LaneStatusSource => ({
  listAgents: (adopt) => parseAgentList(run(['agent', 'list']), adopt),
  setTitle: (pane, title) => {
    try {
      run(titleArguments(pane, title))
      return null
    } catch (error) {
      return `${pane}: ${error instanceof Error ? error.message : String(error)}`
    }
  },
  labelOwnPane: (label) => {
    if (!ownPane) return
    try {
      run(renameArguments(ownPane, label))
    } catch {
      // The label is decoration: a herdr that cannot be asked must not stop the caller.
    }
  },
})

export const herdrLaneStatusSource = createHerdrLaneStatusSource(runHerdr, process.env.HERDR_PANE_ID)
