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

export const TOOL_SUGGEST_SOURCE = {
  id: "tool-suggest",
  label: "tool wrapper suggestions",
  category: "guard",
} as const;

export const TOOL_SUGGEST_SOURCE_ID = TOOL_SUGGEST_SOURCE.id;
const TOOL_SUGGEST_SOURCE_LABEL = TOOL_SUGGEST_SOURCE.label;

interface ToolSuggestRaw {
  ts?: unknown;
  verdict?: unknown;
  ruleId?: unknown;
  command?: unknown;
  source?: unknown;
}

export function defaultToolSuggestPath(): string {
  const stateHome = process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
  return join(stateHome, "tool-suggest", "suggest-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;
  return undefined;
}

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

export function readToolSuggestSource(options: ToolSuggestSourceOptions = {}): ActivitySourceResult {
  const {
    path = defaultToolSuggestPath(),
    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(TOOL_SUGGEST_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 ToolSuggestRaw;
    const verdict = asString(record.verdict);
    const command = asString(record.command);
    const tsSeconds = asFloatSeconds(record.ts);
    if (!verdict || !command || tsSeconds === undefined) {
      skips.record(
        "missing-fields",
        where,
        trimmed,
        `${!verdict ? "verdict" : !command ? "command" : "ts"} is absent or blank`,
      );
      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 ruleId = asString(record.ruleId);
    const source = asString(record.source);

    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: `${TOOL_SUGGEST_SOURCE_ID}:${ordinal}`,
      ts: new Date(tsMs).toISOString(),
      category: TOOL_SUGGEST_SOURCE.category,
      source: TOOL_SUGGEST_SOURCE_ID,
      actor: "agent",
      severity: verdict === "deny" ? "notice" : "info",
      title: `${verdict}${ruleId ? ` (${ruleId})` : ""}${source ? ` via ${source}` : ""}: ${command}`,
      dedupeKey: `${verdict}:${ruleId ?? ""}:${command}`,
      detail: { verdict, ruleId, command, source },
    };

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

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