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

export const NOTIF_GATE_SOURCE = {
  id: "notif-gate",
  label: "alert gate decisions",
  category: "notification",
} as const;

export const NOTIF_GATE_SOURCE_ID = NOTIF_GATE_SOURCE.id;
const NOTIF_GATE_SOURCE_LABEL = NOTIF_GATE_SOURCE.label;

interface NotifGateRaw {
  timestamp?: unknown;
  source_app?: unknown;
  verdict?: unknown;
  title?: unknown;
  ts?: unknown;
  decision?: unknown;
  id?: unknown;
  program?: unknown;
  unit?: unknown;
  channel?: unknown;
  summary?: unknown;
  body?: unknown;
}

export function defaultNotifGatePath(): string {
  const stateHome = process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
  return join(stateHome, "notif-gate", "notif-log.jsonl");
}

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

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

function normalizeSummary(summary: string): string {
  return summary.replace(/\d+/g, "#");
}

function verdictFor(record: NotifGateRaw): "allowed" | "blocked" | undefined {
  const verdict = asString(record.verdict);
  if (verdict === "allowed" || verdict === "blocked") return verdict;

  // Durable records written before the explicit event schema used these names.
  const decision = asString(record.decision);
  if (decision === "delivered") return "allowed";
  if (decision === "suppressed") return "blocked";
  return undefined;
}

function coverage(
  path: string,
  status: "absent" | "error",
  error?: string,
): ActivitySourceResult {
  return {
    events: [],
    skippedEntries: [],
    skippedTruncated: false,
    coverage: {
      id: NOTIF_GATE_SOURCE_ID,
      label: NOTIF_GATE_SOURCE_LABEL,
      category: NOTIF_GATE_SOURCE.category,
      path,
      status,
      records: 0,
      totalRecords: 0,
      skipped: 0,
      ...(error === undefined ? {} : { error }),
    },
  };
}

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

  if (!existsSyncImpl(path)) return coverage(path, "absent");

  let raw: string;
  try {
    raw = readFileImpl(path);
  } catch (error) {
    return coverage(path, "error", error instanceof Error ? error.message : String(error));
  }

  let records = 0;
  let totalRecords = 0;
  const skips = createSkipCollector(NOTIF_GATE_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 NotifGateRaw;
    const summary = asString(record.title) ?? asString(record.summary);
    const tsSeconds = asFloatSeconds(record.timestamp) ?? asFloatSeconds(record.ts);
    if (!summary || tsSeconds === undefined) {
      skips.record("missing-fields", where, trimmed, `${!summary ? "title" : "timestamp"} is absent or blank`);
      continue;
    }
    const tsMs = tsSeconds * 1000;
    if (!Number.isFinite(tsMs)) {
      skips.record("invalid-timestamp", where, trimmed, `timestamp=${String(record.timestamp ?? record.ts)} does not convert to a finite time`);
      continue;
    }

    const verdict = verdictFor(record);
    if (!verdict) {
      skips.record("missing-fields", where, trimmed, "verdict is neither allowed nor blocked");
      continue;
    }

    const program = asString(record.source_app) ?? asString(record.program);
    const body = asString(record.body);

    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 event: ActivityEvent = {
      id: `${NOTIF_GATE_SOURCE_ID}:${ordinal}`,
      ts: new Date(tsMs).toISOString(),
      category: NOTIF_GATE_SOURCE.category,
      source: NOTIF_GATE_SOURCE_ID,
      actor: "system",
      severity: verdict === "blocked" ? "notice" : "info",
      title: `${summary}${body ? ` — ${body}` : ""}`,
      dedupeKey: `${verdict}:${program ?? ""}:${normalizeSummary(summary)}`,
    };

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