import type { AguiMessage } from "@optage/sdk/client";
import type { ChatMessage, AnalysisStateSnapshot, InterruptPayload } from "@optage/sdk/client";

export interface ChatSession {
  id: string;
  repository_id: string;
  thread_id: string;
  title: string;
  messages: ChatMessage[];
  agui_history: AguiMessage[];
  analysis_state: AnalysisStateSnapshot;
  pending_interrupt: InterruptPayload | null;
  created_at: string;
  updated_at: string;
}

export interface SessionSummary {
  id: string;
  title: string;
  updated_at: string;
}

// --- API helpers ---

export async function fetchSessions(repositoryId: string): Promise<SessionSummary[]> {
  const res = await fetch(`/api/sessions?repositoryId=${repositoryId}`);
  if (!res.ok) return [];
  return res.json();
}

export async function fetchSession(id: string): Promise<ChatSession | null> {
  const res = await fetch(`/api/sessions/${id}`);
  if (!res.ok) return null;
  return res.json();
}

export async function createSessionApi(repositoryId: string): Promise<ChatSession> {
  const res = await fetch("/api/sessions", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ repositoryId }),
  });
  return res.json();
}

export async function updateSessionApi(
  id: string,
  data: {
    title?: string;
    messages?: ChatMessage[];
    agui_history?: AguiMessage[];
    analysis_state?: AnalysisStateSnapshot;
    pending_interrupt?: InterruptPayload | null;
  },
): Promise<void> {
  await fetch(`/api/sessions/${id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
}

export async function deleteSessionApi(id: string): Promise<void> {
  await fetch(`/api/sessions/${id}`, { method: "DELETE" });
}

// --- Utilities ---

export function deriveTitle(messages: ChatMessage[]): string {
  const firstUser = messages.find((m) => m.role === "user");
  if (!firstUser) return "New Chat";
  const textBlock = firstUser.blocks.find((b) => b.type === "text");
  if (!textBlock || textBlock.type !== "text") return "New Chat";
  const text = textBlock.text.trim();
  if (text.length <= 40) return text;
  return text.slice(0, 37) + "...";
}

interface DateGroup {
  label: string;
  sessions: SessionSummary[];
}

export function groupByDate(sessions: SessionSummary[]): DateGroup[] {
  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  const yesterdayStart = todayStart - 86400000;
  const weekStart = todayStart - 7 * 86400000;

  const groups: Record<string, SessionSummary[]> = {
    Today: [],
    Yesterday: [],
    "Previous 7 Days": [],
    Older: [],
  };

  const sorted = [...sessions].sort(
    (a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime(),
  );

  for (const s of sorted) {
    const ts = new Date(s.updated_at).getTime();
    if (ts >= todayStart) groups["Today"].push(s);
    else if (ts >= yesterdayStart) groups["Yesterday"].push(s);
    else if (ts >= weekStart) groups["Previous 7 Days"].push(s);
    else groups["Older"].push(s);
  }

  return Object.entries(groups)
    .filter(([, list]) => list.length > 0)
    .map(([label, list]) => ({ label, sessions: list }));
}
