const crypto = require('crypto');

function registerSkillsRoutes(app, { db, ai, memory, skills }) {

  // Get all skills for a division (core + sub-skills)
  app.get('/api/skills/:division_id', (req, res) => {
    const divId = parseInt(req.params.division_id);
    const coreSkills = db.prepare('SELECT * FROM skills WHERE division_id = ? AND parent_id IS NULL ORDER BY use_count DESC').all(divId);
    const allSubSkills = db.prepare('SELECT * FROM skills WHERE division_id = ? AND parent_id IS NOT NULL ORDER BY use_count DESC').all(divId);

    // Attach sub-skills to their parents
    const result = coreSkills.map(core => ({
      ...core,
      sub_skills: allSubSkills.filter(s => s.parent_id === core.id)
    }));

    const stats = {
      total: coreSkills.length + allSubSkills.length,
      embedded: db.prepare('SELECT COUNT(*) as c FROM skills WHERE division_id = ? AND embedding IS NOT NULL').get(divId).c
    };

    res.json({ skills: result, stats });
  });

  // Get ALL skills across all divisions (for global views)
  app.get('/api/skills', (req, res) => {
    const all = db.prepare('SELECT * FROM skills ORDER BY use_count DESC').all();
    const stats = {
      total: all.length,
      embedded: all.filter(s => s.embedding).length,
      stale: all.filter(s => s.use_count === 0).length
    };
    res.json({ skills: all, stats });
  });

  // Create a skill
  app.post('/api/skills', (req, res) => {
    const { division_id, parent_id, name, content, icon, color, tags } = req.body;
    const now = new Date().toISOString();
    const r = db.prepare('INSERT INTO skills (division_id, parent_id, name, content, icon, color, tags, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
      .run(division_id, parent_id || null, name, content, icon || 'fa-lightbulb', color || '#34d399', tags || '', now);
    const skillId = r.lastInsertRowid;

    // Fire-and-forget: embed the new skill
    const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
    memory.embedText(`${name}. ${content}. Tags: ${tags || ''}`, settings).then(vec => {
      if (vec) db.prepare('UPDATE skills SET embedding = ? WHERE id = ?').run(JSON.stringify(vec), skillId);
    }).catch(() => {});

    memory.logMemory(division_id, 'skill_created', `New skill added: "${name}"`);
    res.json({ id: skillId });
  });

  // Update a skill (partial — only updates fields that are provided)
  app.put('/api/skills/:id', (req, res) => {
    const existing = db.prepare('SELECT * FROM skills WHERE id = ?').get(req.params.id);
    if (!existing) return res.status(404).json({ error: 'Skill not found' });

    const name    = req.body.name    ?? existing.name;
    const content = req.body.content ?? existing.content;
    const icon    = req.body.icon    ?? existing.icon;
    const color   = req.body.color   ?? existing.color;
    const tags    = req.body.tags    ?? existing.tags;

    // Clear embedding if content changed (will be re-embedded)
    const contentChanged = content !== existing.content || name !== existing.name;
    db.prepare('UPDATE skills SET name = ?, content = ?, icon = ?, color = ?, tags = ?, embedding = ? WHERE id = ?')
      .run(name, content, icon, color, tags, contentChanged ? null : existing.embedding, req.params.id);

    // Re-embed if content changed
    if (contentChanged) {
      const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
      memory.embedText(`${name}. ${content}. Tags: ${tags || ''}`, settings).then(vec => {
        if (vec) db.prepare('UPDATE skills SET embedding = ? WHERE id = ?').run(JSON.stringify(vec), req.params.id);
      }).catch(() => {});
    }

    res.json({ success: true });
  });

  // Delete a skill (cascades to sub-skills via FK)
  app.delete('/api/skills/:id', (req, res) => {
    // Delete sub-skills first (SQLite FK cascade may not fire for all setups)
    db.prepare('DELETE FROM skills WHERE parent_id = ?').run(req.params.id);
    db.prepare('DELETE FROM skills WHERE id = ?').run(req.params.id);
    res.json({ success: true });
  });

  // AI-assisted skill editing
  app.post('/api/skills/:id/ai-edit', async (req, res) => {
    const { instruction } = req.body;
    const skill = db.prepare('SELECT * FROM skills WHERE id = ?').get(req.params.id);
    if (!skill) return res.status(404).json({ error: 'Skill not found' });

    const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
    const div = db.prepare('SELECT name FROM divisions WHERE id = ?').get(skill.division_id);

    const prompt = `You are editing an operational skill document for the "${div?.name || 'General'}" division of a business.

Current skill name: "${skill.name}"
Current content:
${skill.content}

The director wants you to: ${instruction}

Rewrite the ENTIRE skill content incorporating the requested changes. Keep it actionable, specific, and formatted with clear steps/rules. Do NOT use markdown. Use plain text with newline breaks.

Return ONLY the updated skill content text (no JSON, no quotes, no explanation).`;

    try {
      const newContent = await ai.callAI(prompt, settings, `${ai.buildBusinessContext()} ${ai.buildLanguageInstruction(settings, { plainText: true })}`);
      res.json({ success: true, updated_content: newContent.trim() });
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });

  // Backfill skill embeddings
  app.post('/api/skills/backfill', async (req, res) => {
    const result = await skills.backfillSkillEmbeddings();
    res.json({ message: `Embedded ${result.done}/${result.total} skills.`, ...result });
  });
}

module.exports = { registerSkillsRoutes };
