import { existsSync, readdirSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { ActiveSessionSchema, type ActiveSession } from "./schema";

export function defaultAgentSessionsRoot(): string {
  return process.env.AGENT_SESSIONS_DIR ?? join(homedir(), ".local", "state", "agent-sessions");
}

type ReadActiveSessionsOptions = {
  root?: string;
  existsSyncImpl?: typeof existsSync;
  readdirSyncImpl?: typeof readdirSync;
  readFileImpl?: (path: string) => string;
};

export function readActiveSessions(options: ReadActiveSessionsOptions = {}): ActiveSession[] {
  const {
    root = defaultAgentSessionsRoot(),
    existsSyncImpl = existsSync,
    readdirSyncImpl = readdirSync,
    readFileImpl = (path) => readFileSync(path, "utf8"),
  } = options;

  const sessionsDir = join(root, "sessions");
  if (!existsSyncImpl(sessionsDir)) return [];

  const sessions: ActiveSession[] = [];
  for (const name of readdirSyncImpl(sessionsDir)) {
    if (!name.endsWith(".json")) continue;
    const path = join(sessionsDir, name);
    let raw: unknown;
    try {
      raw = JSON.parse(readFileImpl(path));
    } catch {
      continue;
    }
    if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
    const record = raw as Record<string, unknown>;
    if (record.schemaVersion !== 1) continue;
    if (typeof record.finishedAt === "string" && record.finishedAt.trim().length > 0) continue;

    const parsed = ActiveSessionSchema.safeParse({
      ledgerId: record.ledgerId,
      runtime: record.runtime,
      host: record.host,
      startedAt: record.startedAt,
      ...(typeof record.launchedBy === "string" ? { launchedBy: record.launchedBy } : {}),
      ...(typeof record.worktree === "string" ? { worktree: record.worktree } : {}),
    });
    if (parsed.success) sessions.push(parsed.data);
  }

  return sessions.sort((left, right) => left.ledgerId.localeCompare(right.ledgerId));
}
