import { useMemo, useState } from 'react';
import type { Campaign, Character } from '@/lib/schemas';
import { complete } from '@/lib/llm/client';
import { getLlmConfig, useAssistantStore } from '@/stores/assistantStore';
import { buildCampaignContext } from '@/lib/assistant/context';
import {
  buildLevelUpRoutesPrompt, buildLevelUpStepsPrompt, buildRoutesSchema, buildStepsSchema,
  type BuildRoute, type BuildStep,
} from '@/lib/assistant/prompts';
import { deterministicRoutes, deterministicSteps } from '@/lib/assistant/levelup';

export type AdvisorState = 'idle' | 'loading' | 'ready' | 'error';

export function useLevelUpAdvisor(campaign: Campaign, character: Character) {
  const llmEnabled = useAssistantStore((s) => s.enabled);
  const hasKey = useAssistantStore((s) => !!s.apiKey);
  const canUseLlm = llmEnabled && hasKey;
  const nextLevel = Math.min(20, character.level + 1);

  const ctx = useMemo(
    () => buildCampaignContext({ campaign, characters: [character], encounters: [], quests: [], notes: [] }),
    [campaign, character],
  );

  const [state, setState] = useState<AdvisorState>('idle');
  const [routes, setRoutes] = useState<BuildRoute[] | undefined>();
  const [steps, setSteps] = useState<BuildStep[] | undefined>();
  const [chosen, setChosen] = useState<string | undefined>();
  const [source, setSource] = useState<'llm' | 'deterministic'>('deterministic');
  const [message, setMessage] = useState<string | null>(null);

  const fetchRoutes = async () => {
    setState('loading');
    setMessage(null);
    setSteps(undefined);
    setChosen(undefined);
    if (canUseLlm) {
      const prompt = buildLevelUpRoutesPrompt(ctx, character, nextLevel);
      const res = await complete(getLlmConfig(), { system: prompt.system, user: prompt.user, schema: buildRoutesSchema, maxTokens: 700 });
      if (res.ok && 'data' in res && res.data.routes.length) {
        setRoutes(res.data.routes);
        setSource('llm');
        setState('ready');
        return;
      }
      if (!res.ok) setMessage(`AI unavailable (${res.error}); showing general routes.`);
    }
    setRoutes(deterministicRoutes(campaign.system, character.className));
    setSource('deterministic');
    setState('ready');
  };

  const chooseRoute = async (title: string) => {
    setChosen(title);
    setSteps(undefined);
    if (canUseLlm) {
      const prompt = buildLevelUpStepsPrompt(ctx, character, nextLevel, title);
      const res = await complete(getLlmConfig(), { system: prompt.system, user: prompt.user, schema: buildStepsSchema, maxTokens: 700 });
      if (res.ok && 'data' in res && res.data.steps.length) {
        setSteps(res.data.steps);
        setSource('llm');
        return;
      }
    }
    setSteps(deterministicSteps(campaign.system, character.className, title, nextLevel));
    setSource('deterministic');
  };

  return { state, routes, steps, chosen, source, message, canUseLlm, nextLevel, fetchRoutes, chooseRoute };
}
