import { describe, it, expect } from 'vitest';
import { deterministicRoutes, deterministicSteps } from './levelup';
import { buildRoutesSchema, buildStepsSchema, buildLevelUpRoutesPrompt, buildLevelUpStepsPrompt } from './prompts';
import { buildCampaignContext } from './context';
import { characterDefaults, type Campaign, type Character } from '@/lib/schemas';

function ctxAndChar(system: Campaign['system']) {
  const campaign: Campaign = { id: 'c', name: 'T', system, description: '', createdAt: '', updatedAt: '' };
  const c: Character = {
    id: 'p', campaignId: 'c', system, kind: 'pc', name: 'Hero', ancestry: '', className: 'Cleric', level: 3,
    abilities: { str: 10, dex: 12, con: 13, int: 8, wis: 16, cha: 11 },
    hp: { current: 20, max: 20, temp: 0 }, speed: 30, armorBonus: 0,
    skillRanks: {}, saveRanks: {}, perceptionRank: 'trained',
    ...characterDefaults(), notes: '', createdAt: '', updatedAt: '',
  };
  return { ctx: buildCampaignContext({ campaign, characters: [c], encounters: [], quests: [], notes: [] }), c };
}

describe('deterministic level-up fallback', () => {
  it('returns 4 schema-valid routes for both systems', () => {
    for (const system of ['5e', 'pf2e'] as const) {
      const routes = deterministicRoutes(system, 'Cleric');
      expect(routes).toHaveLength(4);
      expect(buildRoutesSchema.safeParse({ routes }).success).toBe(true);
    }
  });
  it('produces system-appropriate steps (pf2e vs 5e vocabulary)', () => {
    const pf = deterministicSteps('pf2e', 'Cleric', 'Offense', 4);
    const dnd = deterministicSteps('5e', 'Cleric', 'Offense', 4);
    expect(buildStepsSchema.safeParse({ steps: pf }).success).toBe(true);
    expect(JSON.stringify(pf)).toMatch(/ability boosts|skill feat|skill increase/i);
    expect(JSON.stringify(dnd)).toMatch(/ability score improvement|feat/i);
  });
  it('handles a custom route title', () => {
    const steps = deterministicSteps('5e', 'Wizard', 'Blaster control mage', 5);
    expect(steps.length).toBeGreaterThan(0);
    expect(JSON.stringify(steps)).toContain('Blaster control mage');
  });
});

describe('level-up prompts', () => {
  it('routes prompt names the system, class, and next level', () => {
    const { ctx, c } = ctxAndChar('pf2e');
    const { system, user } = buildLevelUpRoutesPrompt(ctx, c, 4);
    expect(system).toMatch(/pathfinder/i);
    expect(user).toContain('Cleric');
    expect(user).toContain('4');
  });
  it('steps prompt includes the chosen route and constrains to the system', () => {
    const { ctx, c } = ctxAndChar('5e');
    const { system, user } = buildLevelUpStepsPrompt(ctx, c, 4, 'Defense');
    expect(system).toMatch(/5e|dungeons/i);
    expect(user).toContain('Defense');
  });
});
