import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { client } from "@/client";
import type { AgentSessionResponse } from "@/client/models/agentSessionResponse";

/**
 * Load personal agent sessions (wk is null — not tied to any workspace).
 */
export function usePersonalSessions() {
  const [sessions, setSessions] = useState<AgentSessionResponse[]>([]);
  const [loading, setLoading] = useState(true);
  const sessionsRef = useRef<AgentSessionResponse[]>([]);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    client
      .agentListSessions()
      .then(({ data }) => {
        if (!cancelled) {
          // Only keep sessions without a workspace
          const personal = data.filter(
            (s) => s.enabled && (s.wk == null || s.wk === ""),
          );
          sessionsRef.current = personal;
          setSessions(personal);
        }
      })
      .catch(() => {})
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const addSession = useCallback((session: AgentSessionResponse) => {
    setSessions((prev) => {
      if (prev.some((s) => s.id === session.id)) return prev;
      return [...prev, session];
    });
  }, []);

  /** Set of personal session IDs for fast lookup */
  const personalSessionIds = useMemo(
    () => new Set(sessions.map((s) => s.id)),
    [sessions],
  );

  return { sessions, loading, sessionsRef, personalSessionIds, addSession };
}

/** Ensure a personal agent session exists (without workspace), creating one if needed. */
export async function ensurePersonalSession(
  existingSessions: AgentSessionResponse[],
): Promise<string | null> {
  const personalSession = existingSessions.find(
    (s) => s.enabled && (s.wk == null || s.wk === ""),
  );
  if (personalSession) return personalSession.id;

  try {
    const modelsRes = await client.aiListModels();
    const modelVersion = modelsRes.data[0]?.id;
    if (!modelVersion) return null;

    const res = await client.agentCreateSession({
      name: "Personal Agent",
      agent_kind: "chat",
      model_version: modelVersion,
      wk: null,
    });
    return res.data.id;
  } catch {
    return null;
  }
}
