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

export const NOTIFICATIONS_SOURCE = {
  id: "notifications",
  label: "notification attempts",
  category: "notification",
} as const;

export const NOTIFICATIONS_SOURCE_ID = NOTIFICATIONS_SOURCE.id;
const NOTIFICATIONS_SOURCE_LABEL = NOTIFICATIONS_SOURCE.label;

interface NotificationsRaw {
  ts?: unknown;
  app?: unknown;
  summary?: unknown;
  body?: unknown;
  urgency?: unknown;
}

export function defaultNotificationsPath(): string {
  return join(homedir(), ".local", "state", "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 severityFromUrgency(urgency: string | undefined): "error" | "notice" | "info" {
  if (urgency === "critical") return "error";
  if (urgency === "normal") return "notice";
  if (urgency === "low") return "info";
  return "info";
}

function truncateBody(body: string | undefined): string {
  return body ? body.slice(0, 200) : "";
}

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

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

  if (!existsSyncImpl(path)) {
    return {
      events: [],
      skippedEntries: [],
      skippedTruncated: false,
      coverage: {
        id: NOTIFICATIONS_SOURCE_ID,
        label: NOTIFICATIONS_SOURCE_LABEL,
        category: NOTIFICATIONS_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: NOTIFICATIONS_SOURCE_ID,
        label: NOTIFICATIONS_SOURCE_LABEL,
        category: NOTIFICATIONS_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(NOTIFICATIONS_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 NotificationsRaw;
    const summary = asString(record.summary);
    if (!summary) {
      skips.record("missing-fields", where, trimmed, "summary is absent or blank");
      continue;
    }

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

    const tsMs = tsSeconds * 1000;
    if (!Number.isFinite(tsMs)) {
      skips.record("invalid-timestamp", where, trimmed, `ts=${String(record.ts)} does not convert to a finite time`);
      continue;
    }

    const app = asString(record.app);
    const body = asString(record.body);
    const titleBody = truncateBody(body);
    const title = `${summary}${titleBody ? ` — ${titleBody}` : ""}`;
    const urgency = asString(record.urgency)?.toLowerCase();

    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: `${NOTIFICATIONS_SOURCE_ID}:${ordinal}`,
      ts: new Date(tsMs).toISOString(),
      category: NOTIFICATIONS_SOURCE.category,
      source: NOTIFICATIONS_SOURCE_ID,
      actor: "system",
      severity: severityFromUrgency(urgency),
      title,
      dedupeKey: `${app ?? ""}:${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: NOTIFICATIONS_SOURCE_ID,
      label: NOTIFICATIONS_SOURCE_LABEL,
      category: NOTIFICATIONS_SOURCE.category,
      path,
      status: "ok",
      records,
      totalRecords,
      skipped: skips.count,
      ...(earliestMs === undefined ? {} : {
        earliest: new Date(earliestMs).toISOString(),
        latest: new Date(latestMs ?? earliestMs).toISOString(),
      }),
    },
  };
}
