import { v as validateAuth } from './auth-DuunT7Cg.js';
import Database from 'better-sqlite3';
import * as fs from 'fs';
import * as path from 'path';
import { s as shooterDataDir } from './shooter-home-4f_HkdGI.js';
import { j as json } from './index-CoD1IJuy.js';
import './shared-server-DaWdgxVh.js';
import 'crypto';
import 'os';

const DB_DIR = shooterDataDir();
const DB_PATH = path.join(DB_DIR, "shooter.db");
const COLUMNS = [
  "id",
  "terminal_id",
  "session_id",
  "project_name",
  "summary",
  "next_steps",
  "trigger",
  "created_at"
];
class SummaryStore {
  db;
  constructor() {
    fs.mkdirSync(DB_DIR, { recursive: true });
    this.db = new Database(DB_PATH);
    this.db.pragma("journal_mode = WAL");
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS session_summaries (
        id           TEXT PRIMARY KEY,
        terminal_id  TEXT,
        session_id   TEXT,
        project_name TEXT,
        summary      TEXT NOT NULL,
        next_steps   TEXT NOT NULL DEFAULT '[]',
        trigger      TEXT NOT NULL,
        created_at   TEXT NOT NULL
      )
    `);
  }
  insert(record) {
    const placeholders = COLUMNS.map(() => "?").join(", ");
    this.db.prepare(`INSERT INTO session_summaries (${COLUMNS.join(", ")}) VALUES (${placeholders})`).run(
      record.id,
      record.terminalId,
      record.sessionId,
      record.projectName,
      record.summary,
      record.nextSteps,
      record.trigger,
      record.createdAt
    );
  }
  listRecent(limit, sessionId) {
    if (sessionId) {
      const rows2 = this.db.prepare(
        "SELECT * FROM session_summaries WHERE session_id = ? ORDER BY created_at DESC LIMIT ?"
      ).all(sessionId, limit);
      return rows2.map(rowToRecord);
    }
    const rows = this.db.prepare("SELECT * FROM session_summaries ORDER BY created_at DESC LIMIT ?").all(limit);
    return rows.map(rowToRecord);
  }
}
function rowToRecord(row) {
  return {
    createdAt: row.created_at,
    id: row.id,
    nextSteps: row.next_steps,
    projectName: row.project_name ?? null,
    sessionId: row.session_id ?? null,
    summary: row.summary,
    terminalId: row.terminal_id ?? null,
    trigger: row.trigger
  };
}
const SS_GLOBAL_KEY = "__shooter_summary_store";
const summaryStore = globalThis[SS_GLOBAL_KEY] || new SummaryStore();
globalThis[SS_GLOBAL_KEY] = summaryStore;
const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 200;
const POST = async ({ request }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  const rawBody = await request.json();
  if (!rawBody || typeof rawBody !== "object" || Array.isArray(rawBody)) {
    return json({ error: "Request body must be a JSON object" }, { status: 400 });
  }
  const body = rawBody;
  if (typeof body.id !== "string" || !body.id) {
    return json({ error: "id is required and must be a non-empty string" }, { status: 400 });
  }
  if (body.id.length > 128) {
    return json({ error: "id must be 128 characters or fewer" }, { status: 400 });
  }
  if (typeof body.summary !== "string" || !body.summary) {
    return json({ error: "summary is required and must be a non-empty string" }, { status: 400 });
  }
  if (body.summary.length > 1e3) {
    return json({ error: "summary must be 1000 characters or fewer" }, { status: 400 });
  }
  if (typeof body.trigger !== "string" || !body.trigger) {
    return json({ error: "trigger is required and must be a non-empty string" }, { status: 400 });
  }
  if (body.trigger.length > 64) {
    return json({ error: "trigger must be 64 characters or fewer" }, { status: 400 });
  }
  if (typeof body.createdAt !== "string" || !body.createdAt) {
    return json({ error: "createdAt is required and must be a non-empty string" }, { status: 400 });
  }
  if (body.createdAt.length > 64 || isNaN(Date.parse(body.createdAt))) {
    return json({ error: "createdAt must be a valid ISO 8601 date string" }, { status: 400 });
  }
  if (typeof body.nextSteps === "string" && body.nextSteps.length > 8192) {
    return json({ error: "nextSteps must be 8192 characters or fewer" }, { status: 400 });
  }
  const record = {
    createdAt: body.createdAt,
    id: body.id,
    nextSteps: typeof body.nextSteps === "string" ? body.nextSteps : "[]",
    projectName: typeof body.projectName === "string" ? body.projectName : null,
    sessionId: typeof body.sessionId === "string" ? body.sessionId : null,
    summary: body.summary,
    terminalId: typeof body.terminalId === "string" ? body.terminalId : null,
    trigger: body.trigger
  };
  try {
    summaryStore.insert(record);
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    const isDuplicate = typeof message === "string" && message.includes("UNIQUE constraint failed");
    if (isDuplicate) {
      return json({ error: "Record with this id already exists" }, { status: 409 });
    }
    return json({ error: "Failed to persist summary" }, { status: 500 });
  }
  return json({ id: record.id, success: true }, { status: 201 });
};
const GET = ({ request, url }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  const sessionId = url.searchParams.get("sessionId") ?? void 0;
  const rawLimit = parseInt(url.searchParams.get("limit") || String(DEFAULT_LIMIT));
  const limit = Number.isFinite(rawLimit) && rawLimit >= 1 ? Math.min(rawLimit, MAX_LIMIT) : DEFAULT_LIMIT;
  const summaries = summaryStore.listRecent(limit, sessionId);
  return json({
    count: summaries.length,
    summaries,
    timestamp: (/* @__PURE__ */ new Date()).toISOString()
  });
};

export { GET, POST };
//# sourceMappingURL=_server.ts-DPHRUFYS.js.map
