// Goddess Agent - Complete Redesign

const axios = require('axios');
const { ITEMS, SKILLS, BLESSINGS } = require('../data/gameData');

const LM_STUDIO_URL = 'http://localhost:1234';

const GODDESS_SYSTEM_PROMPT = `You are AETHERA, Goddess of Reincarnation.

YOUR ROLE:
- Greet souls seeking rebirth
- Learn what they desire through natural conversation (2-3 exchanges MAX)
- Secretly judge their character
- Offer a personalized blessing
- Offer themed starting items (with emojis: 🗡️🪄📔🧪📜🛡️💍)
- Recommend a world
- Give a prophecy
- Send them forth

CRITICAL RULES:
- Keep responses 60-100 words
- NEVER ask more than 3 questions total
- After 3-4 messages, MUST offer blessing
- After blessing accepted, MUST offer 4 items with emojis
- After item chosen, MUST recommend world
- After world, MUST give prophecy and end
- Use **bold** for important names
- Speak warmly and mystically

FORMAT FOR BLESSING:
"I offer you this blessing:

**[Blessing Name]**

[Description]. This reflects [something personal]."

FORMAT FOR ITEMS (MUST include emojis):
"Choose a gift for your journey:

1. 🪄 **[Item Name]** - [description]
2. 📔 **[Item Name]** - [description]
3. 🧪 **[Item Name]** - [description]
4. 📜 **[Item Name]** - [description]

Or request something different."`;

class GoddessAgent {
  constructor() {
    this.model = 'local-model';
  }

  async generateResponse(state, playerMessage) {
    const messageCount = state.messages?.length || 0;
    
    console.log('\n[GoddessAgent] === GENERATING RESPONSE ===');
    console.log('Message count:', messageCount);
    console.log('State:', {
      blessingOffer: state.blessingOffer,
      blessingAccepted: state.blessingAccepted,
      hasItem: !!state.item,
      hasWorld: !!state.world,
      hasProphecy: !!state.prophecy
    });

    // === FORCED PROGRESSION (No LLM, instant responses) ===
    
    // 1. If item selected but no world → Force world
    if (state.item && !state.world) {
      console.log('→ Forcing WORLD recommendation');
      return this.forceWorld(state, playerMessage);
    }

    // 2. If world selected but no prophecy → Force prophecy
    if (state.world && !state.prophecy) {
      console.log('→ Forcing PROPHECY');
      return this.forceProphecy(state, playerMessage);
    }

    // 3. If 4+ messages and no blessing → Force blessing
    if (messageCount >= 4 && !state.blessingOffer) {
      console.log('→ Forcing BLESSING (4+ messages)');
      return this.forceBlessing(state, playerMessage);
    }

    // 4. If blessing accepted but no items → Force items
    if (state.blessingAccepted && !state.item) {
      console.log('→ Forcing ITEMS (blessing accepted)');
      return this.forceItems(state, playerMessage);
    }

    // === NORMAL LLM GENERATION ===
    console.log('→ Normal LLM generation');
    const prompt = this.buildPrompt(state, playerMessage);

    try {
      const response = await axios.post(`${LM_STUDIO_URL}/v1/chat/completions`, {
        model: this.model,
        messages: [
          { role: 'system', content: GODDESS_SYSTEM_PROMPT },
          { role: 'user', content: prompt }
        ],
        temperature: 0.8,
        max_tokens: 400,
        stream: false
      }, { timeout: 60000 });

      const goddessResponse = response.data.choices[0].message.content;
      const newState = this.parseResponse(state, goddessResponse, playerMessage);

      return {
        response: goddessResponse,
        state: newState,
        success: true
      };
    } catch (error) {
      console.error('LLM Error:', error.message);
      return {
        response: this.getFallback(state),
        state: state,
        success: false
      };
    }
  }

  buildPrompt(state, playerMessage) {
    const recentMessages = (state.messages || []).slice(-3).map(m => 
      `${m.role === 'player' ? 'Seeker' : 'Aethera'}: ${m.content.substring(0, 150)}`
    ).join('\n');

    return `Current conversation:

${recentMessages}

Seeker's latest: "${playerMessage}"

Your task:
${!state.blessingOffer ? '- Ask 1 question to understand them, then offer blessing' :
  state.blessingAccepted && !state.item ? '- Offer 4 themed items with emojis' :
  state.item && !state.world ? '- Recommend a world that fits their desires' :
  state.world && !state.prophecy ? '- Give prophecy and farewell' :
  '- Continue naturally'}

Respond as Aethera:`;
  }

  parseResponse(state, response, playerMessage) {
    const lower = response.toLowerCase();
    const newState = { ...state };

    // Track answers
    if (playerMessage?.length > 10 && (state.messages?.length || 0) < 6) {
      newState.playerAnswers = [...(state.playerAnswers || []), {
        question: state.lastQuestion || 'What do you seek?',
        answer: playerMessage
      }];
    }

    // Detect blessing acceptance
    if (state.blessingOffer && !state.blessingAccepted) {
      if (lower.includes('accept') || lower.includes('i choose') || lower.includes('yes') || 
          lower === 'ok' || lower.includes('sure') || lower.includes('thank')) {
        console.log('✓ Detected blessing acceptance');
        newState.blessingAccepted = true;
      }
    }

    // Detect item selection (by number 1-4 or by name)
    if (state.itemOptions?.length > 0 && !state.item && playerMessage) {
      const trimmed = playerMessage.trim();
      
      // Try number first
      const numMatch = trimmed.match(/^[1-4]$/);
      if (numMatch) {
        const idx = parseInt(numMatch[0]) - 1;
        newState.item = state.itemOptions[idx];
        newState.itemOptions = null;
        console.log('✓ Detected item selection by number:', newState.item.name);
      } else {
        // Try by name
        const found = state.itemOptions.find(opt => 
          trimmed.toLowerCase().includes(opt.name.toLowerCase())
        );
        if (found) {
          newState.item = found;
          newState.itemOptions = null;
          console.log('✓ Detected item selection by name:', newState.item.name);
        }
      }
    }

    // Detect blessing offer
    if (!state.blessingOffer && lower.includes('i offer') && lower.includes('blessing')) {
      const match = response.match(/\*\*([^*]+)\*\*/);
      if (match) {
        newState.blessingOffer = true;
        newState.blessing = { name: match[1].trim(), description: 'Divine gift' };
        console.log('✓ Detected blessing offer:', newState.blessing.name);
      }
    }

    // Detect item offer (numbered list with emojis)
    if (state.blessingAccepted && !state.item && !state.itemOptions) {
      if (lower.match(/\d\.\s*[🗡️🪄📔🧪📜🛡️💍✨]/) || lower.includes('choose a gift')) {
        console.log('✓ Detected item offer');
        // Items will be set by forceItems, not parsed
      }
    }

    // Detect world
    if (state.item && !state.world && (lower.includes('world') || lower.includes('realm'))) {
      const match = lower.match(/(fantasy|cultivation|dark|academy|wasteland|village)/i);
      if (match) {
        newState.world = { title: match[0] + ' Realm' };
        console.log('✓ Detected world:', newState.world.title);
      }
    }

    // Detect prophecy
    if (state.world && !state.prophecy && (lower.includes('prophecy') || lower.includes('fate'))) {
      const match = response.match(/'([^']+)'|"([^"]+)"/);
      if (match) {
        newState.prophecy = match[1] || match[2];
        console.log('✓ Detected prophecy');
      }
    }

    // Check ready
    if (state.blessingAccepted && state.item && state.world && state.prophecy) {
      newState.ready = true;
      console.log('✓ ALL PHASES COMPLETE - READY!');
    }

    // Add messages
    newState.messages = [...(state.messages || []),
      { role: 'player', content: playerMessage },
      { role: 'goddess', content: response }
    ];

    // Track question
    if (response.includes('?')) {
      newState.lastQuestion = response.split('?')[0].split('\n').pop().trim();
    }

    return newState;
  }

  // === FORCED PROGRESSION RESPONSES ===

  forceBlessing(state, playerMessage) {
    const answers = state.playerAnswers || [];
    const allText = answers.map(a => a.answer.toLowerCase()).join(' ');
    
    // Judge and create blessing
    let blessing = { name: 'Blessing of Potential', desc: 'Your abilities grow with experience' };
    let judgment = 'your balanced heart';
    
    if (allText.includes('rich') || allText.includes('money') || allText.includes('gold')) {
      blessing = { name: 'Blessing of Material Gain', desc: 'Wealth flows toward you' };
      judgment = 'your ambition for wealth';
    } else if (allText.includes('help') || allText.includes('people') || allText.includes('heal')) {
      blessing = { name: 'Blessing of the Healer', desc: 'Your magic restores and protects others' };
      judgment = 'your selfless desire to aid others';
    } else if (allText.includes('power') || allText.includes('master') || allText.includes('strongest')) {
      blessing = { name: 'Blessing of Arcane Mastery', desc: 'You learn spells faster and have more mana' };
      judgment = 'your hunger for power';
    } else if (allText.includes('magic') || allText.includes('spell') || allText.includes('learn')) {
      blessing = { name: 'Blessing of the Scholar', desc: 'Knowledge comes easily to you' };
      judgment = 'your curiosity and desire to learn';
    }

    const response = `*[Aethera's eyes glow with cosmic light]*

"Ah, I have heard enough of your heart's desires."

She raises her hand, and starlight coalesces into a shimmering orb.

"I offer you this blessing:

**${blessing.name}**

${blessing.desc}. This gift reflects ${judgment}."

The orb drifts toward you.

"Do you accept this blessing, or yearn for something different?"`;

    return {
      response,
      state: {
        ...state,
        blessingOffer: true,
        blessing: blessing,
        messages: [...state.messages,
          { role: 'player', content: playerMessage },
          { role: 'goddess', content: response }
        ]
      },
      success: true
    };
  }

  forceItems(state, playerMessage) {
    const answers = state.playerAnswers || [];
    const allText = answers.map(a => a.answer.toLowerCase()).join(' ');
    
    // Theme items based on desires
    let items = [];
    
    if (allText.includes('spell') || allText.includes('magic') || allText.includes('learn')) {
      items = [
        { name: 'Spell Journal', icon: '📔', type: 'book', description: 'Empty pages for recording spells', effects: 'Stores 10 spells' },
        { name: 'Apprentice Wand', icon: '🪄', type: 'weapon', description: 'Channels magical energy', effects: '+5 Magic' },
        { name: 'Mana Potion', icon: '🧪', type: 'consumable', description: 'Restores 50 MP', effects: 'Heal 50 MP' },
        { name: 'Grimoire of Basics', icon: '📕', type: 'book', description: 'Contains fundamental spells', effects: 'Teaches 3 spells' }
      ];
    } else if (allText.includes('village') || allText.includes('peace') || allText.includes('quiet')) {
      items = [
        { name: 'Village Map', icon: '📜', type: 'tool', description: 'Shows surrounding lands', effects: 'Reveal local area' },
        { name: 'Travel Rations', icon: '🍞', type: 'consumable', description: 'Dried meat and hardtack', effects: 'Restore 20 HP' },
        { name: 'Wooden Staff', icon: '🪄', type: 'weapon', description: 'A sturdy staff of oak', effects: '+5 Magic' },
        { name: 'Healing Potion', icon: '🧪', type: 'consumable', description: 'Restores 50 HP', effects: 'Heal 50 HP' }
      ];
    } else if (allText.includes('power') || allText.includes('fight') || allText.includes('strong')) {
      items = [
        { name: 'Iron Sword', icon: '🗡️', type: 'weapon', description: 'A basic iron blade', effects: '+5 Attack' },
        { name: 'Leather Tunic', icon: '🛡️', type: 'armor', description: 'Supple leather armor', effects: '+8 Defense' },
        { name: 'Health Potion', icon: '🧪', type: 'consumable', description: 'Restores 50 HP', effects: 'Heal 50 HP' },
        { name: 'Regional Map', icon: '📜', type: 'tool', description: 'Detailed map of region', effects: 'Reveal region' }
      ];
    } else {
      items = [
        { name: 'Spell Journal', icon: '📔', type: 'book', description: 'Empty pages for spells', effects: 'Stores 10 spells' },
        { name: 'Apprentice Wand', icon: '🪄', type: 'weapon', description: 'Channels magical energy', effects: '+5 Magic' },
        { name: 'Mana Potion', icon: '🧪', type: 'consumable', description: 'Restores 50 MP', effects: 'Heal 50 MP' },
        { name: 'Village Map', icon: '📜', type: 'tool', description: 'Shows surrounding lands', effects: 'Reveal local area' }
      ];
    }

    const response = `*[Aethera gestures, and four items materialize before you]*

"Choose a gift for your journey:

1. ${items[0].icon} **${items[0].name}** - ${items[0].description}
2. ${items[1].icon} **${items[1].name}** - ${items[1].description}
3. ${items[2].icon} **${items[2].name}** - ${items[2].description}
4. ${items[3].icon} **${items[3].name}** - ${items[3].description}

Or request something different."`;

    return {
      response,
      state: {
        ...state,
        itemOptions: items,
        messages: [...state.messages,
          { role: 'player', content: playerMessage },
          { role: 'goddess', content: response }
        ]
      },
      success: true
    };
  }

  forceWorld(state, playerMessage) {
    const answers = state.playerAnswers || [];
    const allText = answers.map(a => a.answer.toLowerCase()).join(' ');
    
    let world = { title: 'Fantasy Realm', desc: 'A land where magic and mystery intertwine' };
    
    if (allText.includes('village') || allText.includes('peace') || allText.includes('quiet')) {
      world = { title: 'Fantasy Realm', desc: 'Rolling hills dotted with small villages' };
    } else if (allText.includes('power') || allText.includes('master') || allText.includes('compete')) {
      world = { title: 'Magical Academy', desc: 'Where ambitious mages compete for glory' };
    } else if (allText.includes('dark') || allText.includes('horror') || allText.includes('danger')) {
      world = { title: 'Dark Fantasy', desc: 'A grim realm of gothic horror' };
    }

    const response = `*[Aethera raises both hands, and a vision shimmers before you]*

"Your choice is made. I see the world that calls to your spirit..."

**${world.title}**

${world.desc}. This realm shall be your new home.

"Does this world resonate with your soul?"`;

    return {
      response,
      state: {
        ...state,
        world: world,
        messages: [...state.messages,
          { role: 'player', content: playerMessage },
          { role: 'goddess', content: response }
        ]
      },
      success: true
    };
  }

  forceProphecy(state, playerMessage) {
    const prophecies = [
      "Your spells shall weave the fate of nations.",
      "Riches await, but wisdom must guide your hand.",
      "Those you aid shall become your greatest allies.",
      "The magic you create shall outlive you by centuries.",
      "Power corrupts - your heart shall be tested."
    ];
    
    const prophecy = prophecies[Math.floor(Math.random() * prophecies.length)];
    
    const response = `*[Aethera's eyes glow with cosmic fire as she places a hand on your forehead]*

"Your path is set. Hear this prophecy:"

**"${prophecy}"**

She steps back, and the Threshold dissolves.

"Go forth, ${state.playerName || 'seeker'}. Your new life begins NOW."`;

    return {
      response,
      state: {
        ...state,
        prophecy: prophecy,
        ready: true,
        messages: [...state.messages,
          { role: 'player', content: playerMessage },
          { role: 'goddess', content: response }
        ]
      },
      success: true
    };
  }

  getFallback(state) {
    if (!state.blessingOffer) return "Tell me, seeker... what do you desire in your new existence?";
    if (!state.item) return "Do you accept this blessing?";
    if (!state.world) return "Choose your gift.";
    if (!state.prophecy) return "A world awaits you.";
    return "Go forth, and forge your destiny.";
  }

  getInitialGreeting(playerName) {
    return {
      response: `*[A luminous figure materializes before you, her form shifting between countless aspects. Stars swirl in her eyes.]*

"I am Aethera," she speaks, and her words resonate in your very soul. "Keeper of the Cycle, Guide of Transmigrating Souls."

She regards you with warmth beyond measure.

"Welcome, **${playerName}**. Your previous journey has ended... but here, a new story awaits."

The goddess extends her hand.

"Tell me... what do you seek in this new existence?"`,
      state: {
        phase: 'greeting',
        playerName: playerName,
        playerAnswers: [],
        blessing: null,
        blessingOffer: false,
        blessingAccepted: false,
        item: null,
        itemOptions: null,
        world: null,
        prophecy: null,
        messages: [],
        lastQuestion: '',
        ready: false
      },
      success: true
    };
  }
}

module.exports = GoddessAgent;
