import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { redactBrowserValue } from "../../redact";
import { createSkipCollector } from "../skipped";
import { type ActivityEvent, type ActivitySourceResult, type ReaperSourceOptions } from "../types";

export const REAPER_SOURCE = {
  id: "reaper",
  label: "agent reaper",
  category: "guard",
} as const;

export const REAPER_SOURCE_ID = REAPER_SOURCE.id;
const REAPER_SOURCE_LABEL = REAPER_SOURCE.label;

interface ReaperRaw {
  ts?: unknown;
  action?: unknown;
  root?: unknown;
}

const ACTION_META: Record<string, { title: string; severity: "debug" | "info" | "notice" | "warn" | "error" }> = {
  auto_unblock: { title: "auto-unblocked a stuck turn (killed the blocked tool subtree)", severity: "notice" },
  unblock_refused: { title: "declined to auto-unblock: criteria no longer held", severity: "info" },
  runtime_reap_refused: { title: "declined to reap runtime: criteria no longer held", severity: "info" },
  enforce_refused: { title: "declined to enforce: criteria no longer held", severity: "info" },
  sidecar_reap: { title: "reaped an orphaned sidecar daemon", severity: "notice" },
  sidecar_reap_refused: { title: "declined to reap sidecar: criteria no longer held", severity: "info" },
  runtime_reap: { title: "reaped an orphaned dev-runtime tree", severity: "notice" },
  reap_SIGTERM: { title: "enforcement kill ladder — SIGTERM", severity: "warn" },
  SIGTERM: { title: "enforcement kill ladder — SIGTERM", severity: "warn" },
  reap_SIGKILL: { title: "enforcement kill ladder — SIGKILL", severity: "warn" },
  SIGKILL: { title: "enforcement kill ladder — SIGKILL", severity: "warn" },
  reaped: { title: "enforcement kill completed", severity: "warn" },
};

export function defaultReaperPath(): string {
  return join(homedir(), ".claude", "run", "agent-reaper.log");
}

function asString(value: unknown): string | undefined {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed.length === 0 ? undefined : trimmed;
  }
  return undefined;
}

function asMillisFromSeconds(value: unknown): number | undefined {
  if (typeof value === "number" && Number.isFinite(value)) return value * 1000;
  if (typeof value === "string") {
    const parsed = Number.parseFloat(value);
    return Number.isFinite(parsed) ? parsed * 1000 : undefined;
  }
  return undefined;
}

export function readReaperSource(options: ReaperSourceOptions = {}): ActivitySourceResult {
  const {
    path = defaultReaperPath(),
    readFileImpl = (path) => readFileSync(path, "utf8"),
    existsSyncImpl = existsSync,
    fromMs,
    toMs,
    collectSkipped = false,
  } = options;

  if (!existsSyncImpl(path)) {
    return {
      events: [],
      skippedEntries: [],
      skippedTruncated: false,
      coverage: {
        id: REAPER_SOURCE_ID,
        label: REAPER_SOURCE_LABEL,
        category: REAPER_SOURCE.category,
        path,
        status: "absent",
        records: 0,
        totalRecords: 0,
        skipped: 0,
      },
    };
  }

  let raw: string;
  try {
    raw = readFileImpl(path);
  } catch (error) {
    return {
      events: [],
      skippedEntries: [],
      skippedTruncated: false,
      coverage: {
        id: REAPER_SOURCE_ID,
        label: REAPER_SOURCE_LABEL,
        category: REAPER_SOURCE.category,
        path,
        status: "error",
        records: 0,
        totalRecords: 0,
        skipped: 0,
        error: error instanceof Error ? error.message : String(error),
      },
    };
  }

  let records = 0;
  let totalRecords = 0;
  const skips = createSkipCollector(REAPER_SOURCE_ID, collectSkipped);
  let earliestMs: number | undefined;
  let latestMs: number | undefined;
  let ordinal = 0;
  let lineNumber = 0;
  const events: ActivityEvent[] = [];

  for (const line of raw.split("\n")) {
    lineNumber += 1;
    const trimmed = line.trim();
    if (!trimmed) continue;
    ordinal += 1;
    const where = { path: path, line: lineNumber };

    let parsed: unknown;
    try {
      parsed = JSON.parse(trimmed);
    } catch {
      skips.record("unparseable-json", where, trimmed);
      continue;
    }
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
      skips.record("not-an-object", where, trimmed);
      continue;
    }

    const record = parsed as ReaperRaw;
    const action = asString(record.action);
    if (!action) {
      skips.record("missing-fields", where, trimmed, "action is absent or blank");
      continue;
    }

    const tsMs = asMillisFromSeconds(record.ts);
    if (tsMs === undefined || !Number.isFinite(tsMs)) {
      skips.record("invalid-timestamp", where, trimmed, `ts=${String(record.ts)} is not epoch seconds`);
      continue;
    }

    totalRecords += 1;
    if (earliestMs === undefined || tsMs < earliestMs) earliestMs = tsMs;
    if (latestMs === undefined || tsMs > latestMs) latestMs = tsMs;

    if (fromMs !== undefined && tsMs < fromMs) continue;
    if (toMs !== undefined && tsMs > toMs) continue;

    const meta = ACTION_META[action] ?? { title: action, severity: "info" as const };
    const event: ActivityEvent = {
      id: `${REAPER_SOURCE_ID}:${ordinal}`,
      ts: new Date(tsMs).toISOString(),
      category: REAPER_SOURCE.category,
      source: REAPER_SOURCE_ID,
      actor: "system",
      severity: meta.severity,
      title: meta.title,
      dedupeKey: action,
    };
    const root = asString(record.root);
    if (root) {
      event.session = root;
    }
    const redacted = redactBrowserValue(parsed);
    if (redacted && typeof redacted === "object" && !Array.isArray(redacted)) {
      event.detail = redacted as Record<string, unknown>;
    }

    events.push(event);
    records += 1;
  }

  return {
    events,
    skippedEntries: skips.entries,
    skippedTruncated: skips.truncated,
    coverage: {
      id: REAPER_SOURCE_ID,
      label: REAPER_SOURCE_LABEL,
      category: REAPER_SOURCE.category,
      path,
      status: "ok",
      records,
      totalRecords,
      skipped: skips.count,
      ...(earliestMs === undefined ? {} : {
        earliest: new Date(earliestMs).toISOString(),
        latest: new Date(latestMs ?? earliestMs).toISOString(),
      }),
    },
  };
}
