function createBriefingService({ db, callAI }) {
  let briefingCache = { key: '', data: null };
  const BRIEFING_TIMEOUT_MS = 8000;

  function getLanguageConfig(language) {
    const lang = ['en', 'it', 'ro'].includes(language) ? language : 'en';
    const configs = {
      en: {
        aiLabel: 'English',
        dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        fallback: (owner) => ({
          greeting: `Good morning, ${owner}! Let's make today count.`,
          focus_division: 'DIVISION 2',
          focus_reason: 'Marketing drives all revenue. Start the day generating new leads.',
          priorities: ['Log today\'s metrics in all divisions', 'Check pending tasks for active clients', 'Review daily battle plans'],
          hat_schedule: [
            { time: '9:00-11:00', hat: 'DIVISION 2 (Marketing)', action: 'Cold outreach, lead generation, strategy calls' },
            { time: '11:00-13:00', hat: 'DIVISION 4 (Tech)', action: 'Deep work — build, code, create' },
            { time: '14:00-17:00', hat: 'DIVISION 3 & 6', action: 'Invoicing, client updates, reviews' }
          ]
        })
      },
      it: {
        aiLabel: 'Italian',
        dayNames: ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'],
        fallback: (owner) => ({
          greeting: `Buongiorno, ${owner}! Facciamo contare questa giornata.`,
          focus_division: 'DIVISIONE 2',
          focus_reason: 'Il marketing guida tutta la crescita. Inizia la giornata generando nuovi lead.',
          priorities: ['Registra le metriche di oggi in tutte le divisioni', 'Controlla i task pendenti dei clienti attivi', 'Rivedi i battle plan giornalieri'],
          hat_schedule: [
            { time: '9:00-11:00', hat: 'DIVISIONE 2 (Marketing)', action: 'Outreach, lead generation e strategy call' },
            { time: '11:00-13:00', hat: 'DIVISIONE 4 (Tech)', action: 'Deep work su build, codice e delivery' },
            { time: '14:00-17:00', hat: 'DIVISIONE 3 & 6', action: 'Fatture, aggiornamenti clienti e review' }
          ]
        })
      },
      ro: {
        aiLabel: 'Romanian',
        dayNames: ['Duminică', 'Luni', 'Marți', 'Miercuri', 'Joi', 'Vineri', 'Sâmbătă'],
        fallback: (owner) => ({
          greeting: `Bună dimineața, ${owner}! Hai să facem ziua asta să conteze.`,
          focus_division: 'DIVIZIA 2',
          focus_reason: 'Marketingul alimentează tot venitul. Începe ziua prin generarea de lead-uri noi.',
          priorities: ['Înregistrează metricile de azi în toate diviziile', 'Verifică task-urile restante pentru clienții activi', 'Revizuiește battle plan-urile zilnice'],
          hat_schedule: [
            { time: '9:00-11:00', hat: 'DIVIZIA 2 (Marketing)', action: 'Outreach, generare lead-uri și apeluri de strategie' },
            { time: '11:00-13:00', hat: 'DIVIZIA 4 (Tech)', action: 'Deep work pe build, cod și execuție' },
            { time: '14:00-17:00', hat: 'DIVIZIA 3 & 6', action: 'Facturi, update-uri către clienți și review-uri' }
          ]
        })
      }
    };
    return configs[lang];
  }

  async function generateBriefing(forceRegen = false) {
    const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
    const todayStr = new Date().toISOString().split('T')[0];
    const language = 'en';
    const cacheKey = `${todayStr}:${language}`;
    const languageConfig = getLanguageConfig(language);

    if (briefingCache.key === cacheKey && briefingCache.data && !forceRegen) {
      return briefingCache.data;
    }

    const items = db.prepare('SELECT i.*, d.name as div_name FROM items i JOIN divisions d ON i.division_id = d.id').all();
    const todos = db.prepare('SELECT * FROM todos WHERE done = 0').all();
    const overdue = db.prepare("SELECT bp.title, d.name as div_name FROM battle_plans bp JOIN divisions d ON bp.division_id = d.id WHERE bp.done = 0 AND bp.period = 'daily' AND date(bp.created_at) < date('now')").all();
    const noMetrics = db.prepare("SELECT DISTINCT division_id FROM metrics_config WHERE division_id NOT IN (SELECT DISTINCT division_id FROM metrics_data WHERE date = ? AND is_mock = 0)").all(todayStr);

    const snapshot = {
      total_clients: items.length,
      pending_tasks: todos.length,
      overdue_daily_plans: overdue.length,
      divisions_missing_metrics: noMetrics.length,
      pipeline: items.map((item) => `${item.title} (${item.div_name})`).slice(0, 10).join(', ')
    };

    const owner = settings.owner_name || 'Boss';
    const dow = languageConfig.dayNames[new Date().getDay()];

    try {
      const prompt = `You are the AI Chief of Staff for ${owner}'s agency.
Today is ${dow}, ${todayStr}.
Business snapshot:
- Active clients/projects: ${snapshot.total_clients}
- Pending tasks across all divisions: ${snapshot.pending_tasks}
- Overdue daily battle plans: ${snapshot.overdue_daily_plans}
- Divisions missing today's metrics: ${snapshot.divisions_missing_metrics}
- Active pipeline: ${snapshot.pipeline}

Generate a concise morning briefing in ${languageConfig.aiLabel}. Return ONLY a raw JSON object with these exact keys:
{
  "greeting": "one personalized sentence greeting for ${owner}",
  "focus_division": "name of the single most important division to focus on today (pick the most critical)",
  "focus_reason": "one sentence why",
  "priorities": ["priority 1 (max 12 words)", "priority 2", "priority 3"],
  "hat_schedule": [{"time":"9:00-11:00","hat":"Division Name","action":"what to do"},{"time":"11:00-13:00","hat":"...","action":"..."},{"time":"14:00-17:00","hat":"...","action":"..."}]
}`;

      const aiText = await Promise.race([
        callAI(prompt, settings, ''),
        new Promise((_, reject) => setTimeout(() => reject(new Error('Briefing AI timeout')), BRIEFING_TIMEOUT_MS))
      ]);
      const parsed = JSON.parse(aiText.replace(/```json/gi, '').replace(/```/g, '').trim());

      if (typeof parsed === 'object' && !Array.isArray(parsed) && parsed.greeting) {
        briefingCache = { key: cacheKey, data: { ...parsed, generated_at: new Date().toISOString(), snapshot, language } };
        return briefingCache.data;
      }
      throw new Error('Invalid AI response structure');
    } catch (error) {
      const fallback = {
        ...languageConfig.fallback(owner),
        generated_at: new Date().toISOString(),
        snapshot,
        language,
        fallback: true
      };
      briefingCache = { key: cacheKey, data: fallback };
      return fallback;
    }
  }

  function invalidateBriefingCache() {
    briefingCache = { key: '', data: null };
  }

  return {
    generateBriefing,
    invalidateBriefingCache
  };
}

module.exports = { createBriefingService };
