import { readdirSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { defaultProjectsDirectory, followTailLines, projectDirectoryOf } from '../context/session-log'
import { MS_PER_MINUTE } from '../plan-format/clock'
import { boundedMemo } from '../shared/bounded-memo'
import { stampOf } from '../shared/stat-cache'
import { DEFAULT_SKILL_PREFIX } from '../sync/init'
import { readApprovalRequests } from '../watch/approvals'
import { type LaneSubagents, withSubagentLines } from './activity-read'
import {
  type RunningSubagent,
  runningSubagents,
  SUBAGENT_STALE_MINUTES,
  type SubagentLog,
  subagentsByLane,
} from './subagents'
import type { LaneWorktrees } from './unlisted-lanes'

export type SubagentSource = {
  projects: string
  /** The main checkout whose sessions are read. */
  root: string
  /** The main checkout whose `.jackherd/approvals/` holds the gate's requests. */
  approvalsRoot: string
  /** The absolute worktree directory. */
  worktreeDirectory: string
  /** The lanes placed in worktrees of another name (`PlansSettings.laneWorktrees`). */
  laneWorktrees?: LaneWorktrees
  /** The project's `skillPrefix`, which its copies of the review agents carry; without it only the default one counts. */
  skillPrefix?: string
}

/** The source of the main checkout `root`: Claude Code's own session logs, the gate's requests in the checkout itself. */
export const subagentSourceOf = (
  root: string,
  worktreeDirectory: string,
  skillPrefix?: string,
  laneWorktrees?: LaneWorktrees,
): SubagentSource => ({
  projects: defaultProjectsDirectory(),
  root,
  approvalsRoot: root,
  worktreeDirectory,
  laneWorktrees,
  skillPrefix,
})

/** The end of a log that holds the directory of the last entries. */
const TAIL_BYTES = 64 * 1024
const META_FILE = /^agent-([0-9a-f]+)\.meta\.json$/
/** A request the gate holds is reported for this long, as by the watcher. */
const OPEN_REQUEST_MINUTES = 30

const directoriesOf = (path: string): string[] => {
  try {
    return readdirSync(path, { withFileTypes: true }).flatMap((entry) => (entry.isDirectory() ? [entry.name] : []))
  } catch {
    return []
  }
}

/** How many directories keep their listing: one `subagents` directory per session, a few hundred in a busy project. */
const LISTED_DIRECTORIES = 2048

const listings = boundedMemo<string, { modifiedAt: number; names: string[] }>(LISTED_DIRECTORIES)

/**
 * The entry names of `path`, listed again only when the directory changed since (a file added or removed moves its
 * modification time, a write into a file does not); none when it is missing or cannot be read.
 */
const namesIn = (path: string): string[] => {
  try {
    const modifiedAt = statSync(path).mtimeMs
    const kept = listings.get(path)
    if (kept?.modifiedAt === modifiedAt) return kept.names
    return listings.set(path, { modifiedAt, names: readdirSync(path) }).names
  } catch {
    return []
  }
}

const logOf = (directory: string, name: string, id: string, now: number): SubagentLog[] => {
  try {
    const logPath = join(directory, `agent-${id}.jsonl`)
    const modifiedAt = statSync(logPath).mtimeMs
    if (now - modifiedAt > SUBAGENT_STALE_MINUTES * MS_PER_MINUTE) return []
    const meta: unknown = JSON.parse(readFileSync(join(directory, name), 'utf8'))
    return [{ id, meta, modifiedAt, tail: followTailLines(logPath, TAIL_BYTES) }]
  } catch {
    return []
  }
}

/** The subagent logs of one session's `subagents` directory. */
const logsInSession = (directory: string, now: number): SubagentLog[] =>
  namesIn(directory).flatMap((name) => {
    const id = META_FILE.exec(name)?.[1]
    return id ? logOf(directory, name, id, now) : []
  })

/**
 * How long a session's own log may be untouched before its subagents are no longer looked for: a subagent runs while
 * its session does, and a day is far beyond any subagent's run. Without it, every read checked each log of every past
 * session (about 2,000 in a busy project), when none of them could be running.
 */
export const QUIET_SESSION_MS = 24 * 60 * MS_PER_MINUTE

/** Whether the session's own log was written within `QUIET_SESSION_MS`; a session without a readable log counts as live. */
const isSessionLive = (project: string, session: string, now: number): boolean => {
  const stamp = stampOf(join(project, `${session}.jsonl`))
  return stamp === null || now - stamp.mtimeMs <= QUIET_SESSION_MS
}

/** The `subagents` directory of every session in one project directory that may still run one. */
const sessionDirectoriesOf = (project: string, now: number): string[] =>
  directoriesOf(project)
    .filter((session) => isSessionLive(project, session, now))
    .map((session) => join(project, session, 'subagents'))

/**
 * The project directories Claude Code keeps for sessions started in the main checkout `root` and, when
 * `worktreeDirectory` is given, in a worktree below it: a lane's own subagents, its reviews among them, live there.
 */
const projectDirectoriesOf = (projects: string, root: string, worktreeDirectory?: string): string[] => {
  const main = projectDirectoryOf(root)
  const lanes = worktreeDirectory === undefined ? null : `${projectDirectoryOf(worktreeDirectory)}-`
  return directoriesOf(projects).filter((name) => name === main || (lanes !== null && name.startsWith(lanes)))
}

/** The `subagents` directory of every session of the main checkout and its worktrees. */
const allSessionDirectories = (projects: string, root: string, now: number, worktreeDirectory?: string): string[] =>
  projectDirectoriesOf(projects, root, worktreeDirectory).flatMap((name) =>
    sessionDirectoriesOf(join(projects, name), now),
  )

/**
 * The subagents with a recently written log in the sessions started in the main checkout `root` and its worktrees,
 * from Claude Code's `<projects>/<project>/<session>/subagents/agent-<id>.{meta.json,jsonl}`; whatever cannot be read
 * is left out.
 */
export const readSubagentLogs = (
  projects: string,
  root: string,
  now: number,
  worktreeDirectory?: string,
): SubagentLog[] =>
  allSessionDirectories(projects, root, now, worktreeDirectory).flatMap((directory) => logsInSession(directory, now))

/** The names the gate holds an open request under, as the watcher reads them. */
const heldNames = (root: string, now: number): Set<string> =>
  new Set(
    readApprovalRequests(root)
      .filter((request) => request.usedAt === null && now - request.createdAt <= OPEN_REQUEST_MINUTES * MS_PER_MINUTE)
      .map((request) => request.lane),
  )

/** The running subagents among `logs`, the finished and the stale left out. */
const runningOf = (
  logs: readonly SubagentLog[],
  { approvalsRoot, worktreeDirectory, skillPrefix }: SubagentSource,
  now: number,
): RunningSubagent[] =>
  runningSubagents(
    logs,
    heldNames(approvalsRoot, now),
    now,
    worktreeDirectory,
    skillPrefix === undefined ? [DEFAULT_SKILL_PREFIX] : [DEFAULT_SKILL_PREFIX, skillPrefix],
  )

/**
 * The subagents at work in the sessions of the main checkout and its worktrees: their logs read, the finished and the
 * stale left out. The one chain the herd (`readSubagentActivitySliced`) and the watcher's heartbeat share.
 */
export const readRunningSubagents = (source: SubagentSource, now: number = Date.now()): RunningSubagent[] =>
  runningOf(readSubagentLogs(source.projects, source.root, now, source.worktreeDirectory), source, now)

/**
 * The state of every worktree a subagent of the main checkout's sessions works in, with `pass` awaited before each
 * session's subagents are read, so a gate (`createSliceGate`) can hand the event loop back between them.
 */
export const readSubagentActivitySliced = async (
  source: SubagentSource,
  pass: () => Promise<void>,
  now: number = Date.now(),
): Promise<Map<string, LaneSubagents>> => {
  const logs: SubagentLog[] = []
  for (const directory of allSessionDirectories(source.projects, source.root, now, source.worktreeDirectory)) {
    await pass()
    logs.push(...logsInSession(directory, now))
  }
  const running = runningOf(logs, source, now)
  return withSubagentLines(
    subagentsByLane(running, source.worktreeDirectory, source.laneWorktrees),
    running,
    logs,
    source.worktreeDirectory,
    source.laneWorktrees,
  )
}
