import { writable } from "svelte/store";
import {
  aiHealth as aiHealthCommand,
  aiChat as aiChatCommand,
  coachDaily,
  coachEvening,
  coachWeekly,
  type AiHealthDto,
  type CoachPlanDto,
  type CoachSessionPayload,
} from "$lib/backend/ai";

// ── Store shapes ────────────────────────────────────────────────

type AiStatusState = {
  checking: boolean;
  health: AiHealthDto | null;
};

type CoachState = {
  busy: boolean;
  error: string;
  plan: CoachPlanDto | null;
  kind: string;
};

export type ChatMessage = {
  role: "user" | "assistant" | "error";
  text: string;
};

type ChatState = {
  busy: boolean;
  messages: ChatMessage[];
};

// ── Stores ──────────────────────────────────────────────────────

export const aiStatusStore = writable<AiStatusState>({
  checking: false,
  health: null,
});

export const coachStateStore = writable<CoachState>({
  busy: false,
  error: "",
  plan: null,
  kind: "",
});

export const chatStateStore = writable<ChatState>({
  busy: false,
  messages: [],
});

// ── Actions ─────────────────────────────────────────────────────

export async function checkAiHealth(): Promise<void> {
  aiStatusStore.update((s) => ({ ...s, checking: true }));
  try {
    const health = await aiHealthCommand();
    aiStatusStore.set({ checking: false, health });
  } catch (error) {
    aiStatusStore.set({
      checking: false,
      health: {
        provider: "",
        enabled: false,
        healthy: false,
        message: error instanceof Error ? error.message : String(error),
      },
    });
  }
}

const sessionRunners: Record<
  string,
  (payload: CoachSessionPayload) => Promise<CoachPlanDto>
> = {
  daily: coachDaily,
  evening: coachEvening,
  weekly: coachWeekly,
};

export async function runCoachSession(
  kind: string,
  payload: CoachSessionPayload = {},
): Promise<void> {
  const runner = sessionRunners[kind];
  if (!runner) {
    coachStateStore.set({
      busy: false,
      error: `Unknown coach session kind: ${kind}`,
      plan: null,
      kind,
    });
    return;
  }

  coachStateStore.set({ busy: true, error: "", plan: null, kind });
  try {
    const plan = await runner(payload);
    coachStateStore.set({ busy: false, error: "", plan, kind });
  } catch (error) {
    coachStateStore.set({
      busy: false,
      error: error instanceof Error ? error.message : String(error),
      plan: null,
      kind,
    });
  }
}

export async function runAiChat(prompt: string): Promise<void> {
  chatStateStore.update((s) => ({
    busy: true,
    messages: [...s.messages, { role: "user", text: prompt }],
  }));
  try {
    const response = await aiChatCommand(prompt);
    chatStateStore.update((s) => ({
      busy: false,
      messages: [...s.messages, { role: "assistant", text: response }],
    }));
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    chatStateStore.update((s) => ({
      busy: false,
      messages: [...s.messages, { role: "error", text: msg }],
    }));
  }
}

export function clearCoachPlan(): void {
  coachStateStore.set({ busy: false, error: "", plan: null, kind: "" });
}

export function clearChat(): void {
  chatStateStore.set({ busy: false, messages: [] });
}
