/* EireneEduCloud — AI Learning Assistant ("Ask Eirene AI")
   Eirene Technologies Limited

   On-the-fly content enrichment for learners. Pluggable into ANY LLM endpoint
   (Kenya Education Cloud AI, an on-prem Ollama, or any OpenAI-compatible API) by
   setting window.EE_AI_CONFIG before this script loads:

     window.EE_AI_CONFIG = {
       endpoint: '',   // POST JSON
       apiKey:   '',           // optional bearer token
       model:    'llama3',     // optional
       style:    'openai'      // 'openai' | 'ollama' | 'simple'  (response shape)
     };

   When NO endpoint is configured OR the device is offline, the assistant falls back
   to an on-device, content-derived helper so it ALWAYS responds — no blank screens,
   fully offline. This satisfies "AI enrichment on the go" without a hard dependency
   on connectivity, which matters for low-connectivity Kenyan classrooms. */
(function (w, d) {
  var CFG = w.EE_AI_CONFIG || null;

  function sentences(t) {
    return String(t || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
      .match(/[^.!?]+[.!?]+/g) || [];
  }

  // ---- offline, content-derived fallback (no network) ----
  var Local = {
    explain: function (ctx) {
      var s = sentences(ctx.reading || ctx.text || '');
      var lead = s.slice(0, 2).join(' ');
      return 'In simple terms: ' + (lead || ('"' + ctx.title + '" is part of your ' + (ctx.subject || 'Grade 9') + ' course.')) +
        (ctx.keyTerms && ctx.keyTerms.length ? ' Key idea — ' + ctx.keyTerms[0].term + ': ' + ctx.keyTerms[0].definition : '');
    },
    summarize: function (ctx) {
      var s = sentences(ctx.reading || ctx.text || '');
      var pts = s.slice(0, 3).map(function (x, i) { return (i + 1) + '. ' + x.trim(); });
      if (ctx.keyTerms && ctx.keyTerms.length) pts.push('Key terms: ' + ctx.keyTerms.map(function (k) { return k.term; }).join(', ') + '.');
      return 'Summary of "' + ctx.title + '":\n' + (pts.join('\n') || 'Review the lesson reading and try the quiz.');
    },
    practice: function (ctx) {
      var qs = (ctx.quiz && ctx.quiz.questions) || [];
      if (!qs.length) return 'Try re-reading the lesson, then explain it to a friend in your own words.';
      var q = qs[Math.min(ctx._pi || 0, qs.length - 1)];
      ctx._pi = ((ctx._pi || 0) + 1) % qs.length;
      return 'Practice question:\n' + q.question + '\n' +
        q.options.map(function (o, i) { return String.fromCharCode(65 + i) + ') ' + o; }).join('\n') +
        '\n(Think first — then check: the answer is ' + String.fromCharCode(65 + q.correct) + '.)';
    },
    hint: function (ctx) {
      var qs = (ctx.quiz && ctx.quiz.questions) || [];
      if (qs.length && qs[0].explanation) return 'Hint: ' + qs[0].explanation.split('.')[0] + '.';
      var s = sentences(ctx.reading || '');
      return 'Hint: focus on this — ' + (s[0] || ('the main idea of "' + ctx.title + '"')) + '.';
    },
    ask: function (ctx, q) {
      var s = sentences(ctx.reading || ctx.text || '');
      var ql = q.toLowerCase().split(/\s+/).filter(function (w2) { return w2.length > 3; });
      var hit = s.filter(function (sent) { var l = sent.toLowerCase(); return ql.some(function (k) { return l.indexOf(k) >= 0; }); });
      if (hit.length) return hit.slice(0, 2).join(' ');
      return 'Based on this lesson ("' + ctx.title + '"): ' + (s.slice(0, 2).join(' ') || 'please review the reading above, then ask again.');
    }
  };

  function buildMessages(ctx, instruction) {
    var sys = 'You are Eirene AI, a friendly Grade 9 tutor for the Kenyan CBC. Answer briefly, clearly, ' +
      'and in age-appropriate language. Use Kenyan examples where helpful. Lesson context: "' + ctx.title + '"' +
      (ctx.subject ? ' (' + ctx.subject + ')' : '') + '. Lesson content: ' +
      String(ctx.reading || ctx.text || '').replace(/<[^>]+>/g, ' ').slice(0, 1500);
    return [{ role: 'system', content: sys }, { role: 'user', content: instruction }];
  }

  function callRemote(messages) {
    var body, headers = { 'Content-Type': 'application/json' };
    if (CFG.apiKey) headers['Authorization'] = 'Bearer ' + CFG.apiKey;
    if (CFG.style === 'ollama') body = { model: CFG.model || 'llama3', messages: messages, stream: false };
    else body = { model: CFG.model || 'gpt-4o-mini', messages: messages, temperature: 0.4 };
    return fetch(CFG.endpoint, { method: 'POST', headers: headers, body: JSON.stringify(body) })
      .then(function (r) { if (!r.ok) throw new Error('AI ' + r.status); return r.json(); })
      .then(function (j) {
        return (j.choices && j.choices[0] && j.choices[0].message && j.choices[0].message.content) ||
               (j.message && j.message.content) || j.response || j.reply || '';
      });
  }

  var EireneAI = {
    configured: function () { return !!(CFG && CFG.endpoint); },
    setConfig: function (c) { CFG = c; w.EE_AI_CONFIG = c; },

    // action: 'explain'|'summarize'|'practice'|'hint'|'ask'
    respond: function (action, ctx, userText) {
      var instr = {
        explain: 'Explain this lesson in simpler words for a Grade 9 learner.',
        summarize: 'Summarise the key points of this lesson in 3-4 bullet points.',
        practice: 'Give me one new practice question (with the answer) based on this lesson.',
        hint: 'Give me a helpful hint to understand this lesson.',
        ask: userText || 'Help me understand this lesson.'
      }[action] || (userText || 'Help me.');

      if (this.configured() && (w.navigator ? w.navigator.onLine : true)) {
        return callRemote(buildMessages(ctx, instr)).catch(function () {
          return Local[action] ? Local[action](ctx, userText) : Local.ask(ctx, instr);
        });
      }
      // offline / unconfigured -> instant local fallback (resolved promise)
      var out = Local[action] ? Local[action](ctx, userText) : Local.ask(ctx, instr);
      return w.Promise ? w.Promise.resolve(out) : { then: function (f) { f(out); } };
    },

    mode: function () { return (this.configured() && (!w.navigator || w.navigator.onLine)) ? 'live' : 'offline'; }
  };

  w.EireneAI = EireneAI;
})(window, document);
