import { onMounted, ref } from "vue";

import type { AppInfo, DemoPackSummary, PlayerView, TurnIntent, TurnRequest } from "@contracts";

import { getAppInfo, getDemoPackSummary, getDemoPlayerView } from "./bridge";
import { submitDemoTurn } from "./turnAdapter";

export function useDemo() {
  const appInfo = ref<AppInfo | null>(null);
  const pack = ref<DemoPackSummary | null>(null);
  const playerView = ref<PlayerView | null>(null);
  const loading = ref(true);
  const error = ref<string | null>(null);
  const busy = ref(false);
  const turnError = ref<string | null>(null);
  const lastSubmittedIntent = ref<TurnIntent | null>(null);

  onMounted(async () => {
    try {
      [appInfo.value, pack.value, playerView.value] = await Promise.all([
        getAppInfo(),
        getDemoPackSummary(),
        getDemoPlayerView()
      ]);
    } catch (reason) {
      error.value = reason instanceof Error ? reason.message : String(reason);
    } finally {
      loading.value = false;
    }
  });

  async function submitTurn(intent: "speak_or_act", input: string): Promise<void>;
  async function submitTurn(intent: "continue", input?: ""): Promise<void>;
  async function submitTurn(intent: "speak_or_act" | "continue", input = ""): Promise<void> {
    const currentView = playerView.value;
    const normalizedInput = input.trim();

    if (!currentView || busy.value || (intent === "speak_or_act" && !normalizedInput)) return;

    const request: TurnRequest = {
      storyId: currentView.storyId,
      branchId: currentView.branchId,
      expectedNodeId: currentView.nodeId,
      actionId: `demo_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
      intent,
      input: intent === "continue" ? "" : normalizedInput
    };

    busy.value = true;
    turnError.value = null;
    lastSubmittedIntent.value = intent;

    try {
      const result = await submitDemoTurn(request, currentView);
      playerView.value = result.playerView;
    } catch (reason) {
      turnError.value = reason instanceof Error ? reason.message : String(reason);
    } finally {
      busy.value = false;
    }
  }

  return {
    appInfo,
    busy,
    error,
    lastSubmittedIntent,
    loading,
    pack,
    playerView,
    submitTurn,
    turnError
  };
}
