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 ActionsSourceOptions } from "../types";

export const ACTIONS_SOURCE = {
  id: "actions",
  label: "collector actions",
  category: "service",
} as const;

export const ACTIONS_SOURCE_ID = ACTIONS_SOURCE.id;
const ACTIONS_SOURCE_LABEL = ACTIONS_SOURCE.label;

interface ActionsRaw {
  ts?: unknown;
  verb?: unknown;
  args?: unknown;
  requestedBy?: unknown;
  result?: unknown;
  rc?: unknown;
}

export function defaultActionsPath(): string {
  return join(homedir(), ".local", "state", "overdeck", "actions.jsonl");
}

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

function asNumber(value: unknown): number | undefined {
  if (typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  return undefined;
}

const FAILURE_RESULTS = new Set(["failure", "failed", "error", "denied", "refused", "not allowed", "unsuccessful"]);
const SUCCESS_RESULTS = new Set(["success", "succeeded", "completed", "approved", "allowed", "done"]);

function isFailure(result: string | undefined, rc: number | undefined): boolean {
  if (rc !== undefined && rc !== 0) return true;
  return result !== undefined && FAILURE_RESULTS.has(result.toLowerCase());
}

function outcomeFor(result: string | undefined, rc: number | undefined): Pick<ActivityEvent, "lifecycle" | "result" | "severity"> {
  if (isFailure(result, rc)) return { lifecycle: "failed", result: "failure", severity: "error" };
  if (rc === 0 || (result !== undefined && SUCCESS_RESULTS.has(result.toLowerCase()))) return { lifecycle: "completed", result: "success", severity: "info" };
  return { lifecycle: "unknown", result: "unknown", severity: "info" };
}

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

  if (!existsSyncImpl(path)) {
    return {
      events: [],
      skippedEntries: [],
      skippedTruncated: false,
      coverage: {
        id: ACTIONS_SOURCE_ID,
        label: ACTIONS_SOURCE_LABEL,
        category: ACTIONS_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: ACTIONS_SOURCE_ID,
        label: ACTIONS_SOURCE_LABEL,
        category: ACTIONS_SOURCE.category,
        path,
        status: "error",
        records: 0,
        totalRecords: 0,
        skipped: 0,
        error: error instanceof Error ? error.message : String(error),
      },
    };
  }

  let totalRecords = 0;
  let records = 0;
  const skips = createSkipCollector(ACTIONS_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, 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 ActionsRaw;
    const ts = asString(record.ts);
    const verb = asString(record.verb);
    const result = asString(record.result);
    if (!ts || !verb) {
      skips.record("missing-fields", where, trimmed, `${!ts ? "ts" : "verb"} is absent or blank`);
      continue;
    }

    const tsMs = Date.parse(ts);
    if (!Number.isFinite(tsMs)) {
      skips.record("invalid-timestamp", where, trimmed, `ts=${ts}`);
      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 rc = asNumber(record.rc);
    const outcome = outcomeFor(result, rc);
    const event: ActivityEvent = {
      id: `${ACTIONS_SOURCE_ID}:${ordinal}`,
      ts,
      category: ACTIONS_SOURCE.category,
      source: ACTIONS_SOURCE_ID,
      actor: "human",
      severity: outcome.severity,
      title: `${verb}${result ? ` — ${result}` : ""}`,
      lifecycle: outcome.lifecycle,
      result: outcome.result,
      dedupeKey: verb,
    };

    const session = asString(record.requestedBy);
    if (session) event.session = session;
    if (rc !== undefined) event.rc = rc;

    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: ACTIONS_SOURCE_ID,
      label: ACTIONS_SOURCE_LABEL,
      category: ACTIONS_SOURCE.category,
      path,
      status: "ok",
      records,
      totalRecords,
      skipped: skips.count,
      ...(earliestMs === undefined ? {} : {
        earliest: new Date(earliestMs).toISOString(),
        latest: new Date(latestMs ?? earliestMs).toISOString(),
      }),
    },
  };
}
