// Background Service Worker for Watchman Theological Auditor
// Zero-cost rule-based theological auditor (no API calls)
// 19-point expanded Charter with refined discernment language

// Initialize extension on install
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    chrome.storage.local.set({
      autoAuditEnabled: true,
      auditHistory: [],
      settings: {
        showNotifications: true,
        theme: 'light'
      }
    });
    chrome.tabs.create({ url: 'onboarding.html' });
  }
});

// Core audit function - inline to avoid module issues
function auditTextExpanded(text) {
  if (!text || text.length < 10) {
    return [];
  }

  const findings = [];
  const textLower = text.toLowerCase();

  // Point 1: Scripture Authority
  if (/many christians (now )?believe|modern (scholars|understanding|theologians)|the church (is|has) (reconsidering|evolving)|cultural context suggests|contemporary (understanding|interpretation)/i.test(text)) {
    findings.push({
      charter: "#1 - Scripture Authority",
      tier: "call_to_discernment",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "2 Timothy 3:16-17",
      explanation: "Authority may have shifted from Scripture to cultural consensus or scholarship",
      prompt: "Read the surrounding passage and note who is speaking with authority. Does this reflect Scripture or contemporary opinion?",
      context: "Doctrinal Foundation"
    });
  }

  // Point 2: Christ's Exclusivity
  if (/jesus (as|was) (a|one) moral teacher|many|multiple|various (paths|ways) to god|all religions lead to|valid spiritual path (outside|beyond)|not the only way/i.test(text)) {
    findings.push({
      charter: "#2 - Christ's Exclusivity",
      tier: "pastoral_boundary",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "John 14:6; Acts 4:12",
      explanation: "Christ's exclusivity as Savior and Lord may be diluted or denied",
      prompt: "This touches on salvation itself. Seek Scripture and pastoral counsel before forming conclusions.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 3: Trinitarian Doctrine
  if (/trinity (is|was) (not|never)|jesus (is|was) not (god|divine)|holy spirit (is|was) not|three separate gods/i.test(text)) {
    findings.push({
      charter: "#3 - Trinitarian Doctrine",
      tier: "pastoral_boundary",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "1 John 5:7; Matthew 28:19",
      explanation: "The Trinity (God as Father, Son, and Holy Spirit) is denied or misrepresented",
      prompt: "This is foundational to Christian faith. Compare with Scripture and historic creeds.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 4: Biblical Anthropology
  if (/humans (are|were) (not|never) made in (god's )?image|there (is|was) no soul|consciousness (is|was) purely|material|no spiritual dimension/i.test(text)) {
    findings.push({
      charter: "#4 - Biblical Anthropology",
      tier: "call_to_discernment",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "Genesis 1:27; 1 Thessalonians 5:23",
      explanation: "The biblical view of humans as image-bearers with body, soul, and spirit may be denied",
      prompt: "What does Scripture say about human nature? Test this claim against Genesis and Paul's letters.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 5: Salvation Through Christ
  if (/salvation (is|was) (not|never) through (jesus|christ)|works (can|could) save|faith (is|was) not necessary|grace (is|was) not needed/i.test(text)) {
    findings.push({
      charter: "#5 - Salvation Through Christ",
      tier: "pastoral_boundary",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "Romans 3:24; Ephesians 2:8-9",
      explanation: "Salvation through Christ's work is denied or works-based salvation is implied",
      prompt: "This is the gospel itself. Seek pastoral guidance and study Romans and Ephesians carefully.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 6: Sanctification Process
  if (/sanctification (is|was) (not|never)|holiness (is|was) not|sin (is|was) not (a )?problem|moral transformation (is|was) not/i.test(text)) {
    findings.push({
      charter: "#6 - Sanctification Process",
      tier: "call_to_discernment",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "1 Thessalonians 4:3; Hebrews 12:14",
      explanation: "The call to holiness and moral transformation may be downplayed",
      prompt: "How does Scripture describe the Christian life? Is growth in holiness emphasized?",
      context: "Doctrinal Foundation"
    });
  }

  // Point 7: Moral Objectivity
  if (/morality (is|was) (just|only) personal|right (and|or) wrong (is|are) (not|never) absolute|ethics (are|is) relative|no objective|moral truth/i.test(text)) {
    findings.push({
      charter: "#7 - Moral Objectivity",
      tier: "strong_caution",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "Psalm 119:142; John 17:17",
      explanation: "Objective moral truth grounded in God's character may be replaced with relativism",
      prompt: "Does this reflect biblical ethics or cultural relativism? Compare with Scripture.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 8: Church Authority
  if (/church (has|have) no|pastoral authority (is|was) not|submit (to|was) (not|never)|church leadership (is|was) not|congregational (is|was) only/i.test(text)) {
    findings.push({
      charter: "#8 - Church Authority",
      tier: "call_to_discernment",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "Hebrews 13:17; 1 Peter 5:1-4",
      explanation: "The role of church authority and pastoral leadership may be dismissed",
      prompt: "What does Scripture say about church leadership and submission? Test this against Hebrews and 1 Peter.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 9: Sacramental Understanding
  if (/baptism (is|was) (just|only) symbolic|communion (is|was) (just|only) memorial|sacraments (are|is) (not|never)|no spiritual|grace through|ordinances/i.test(text)) {
    findings.push({
      charter: "#9 - Sacramental Understanding",
      tier: "invitation_to_test",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "Romans 6:3-4; 1 Corinthians 11:23-26",
      explanation: "The spiritual significance of baptism and communion may be reduced to mere symbols",
      prompt: "How does Scripture describe baptism and communion? Are they more than symbols?",
      context: "Doctrinal Foundation"
    });
  }

  // Point 10: Eschatological Clarity
  if (/end times (are|is) (not|never)|resurrection (is|was) (not|never)|heaven (is|was) (not|never)|hell (is|was) (not|never)|judgment (is|was) (not|never)/i.test(text)) {
    findings.push({
      charter: "#10 - Eschatological Clarity",
      tier: "call_to_discernment",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "1 Corinthians 15:54-57; Revelation 20:11-15",
      explanation: "The reality of resurrection, heaven, hell, or final judgment may be denied or spiritualized",
      prompt: "What does Scripture clearly teach about the end times? Test this claim against 1 Corinthians 15 and Revelation.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 11: Pneumatological Accuracy
  if (/holy spirit (is|was) (not|never)|spirit (is|was) (just|only) influence|no spiritual gifts|power (is|was) (not|never)|filling (is|was) (not|never)/i.test(text)) {
    findings.push({
      charter: "#11 - Pneumatological Accuracy",
      tier: "call_to_discernment",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "John 14:26; Acts 1:8; 1 Corinthians 12:4-11",
      explanation: "The person and power of the Holy Spirit may be diminished or denied",
      prompt: "What does Scripture teach about the Holy Spirit's person and work? Compare with John 14-16 and Acts.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 12: Christological Precision
  if (/jesus (was|is) (just|only) human|not (truly|really) god|not (truly|really) human|two natures (is|are) (not|never)|incarnation (is|was) (not|never)/i.test(text)) {
    findings.push({
      charter: "#12 - Christological Precision",
      tier: "pastoral_boundary",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "John 1:1-14; Philippians 2:5-11",
      explanation: "The full humanity and full divinity of Christ (the Incarnation) is denied or confused",
      prompt: "This is central to the gospel. Seek pastoral counsel and study John 1 and Philippians 2 carefully.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 13: Language Integrity
  if (/love (means|is) (just|only) acceptance|no (true|real) love (without|without accepting) sin|love (is|was) (not|never) holy|agape (is|was) (not|never)|truth (is|was) (not|never) loving/i.test(text)) {
    findings.push({
      charter: "#13 - Language Integrity",
      tier: "call_to_discernment",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "1 John 4:8; 1 John 5:3",
      explanation: "Key biblical terms like 'love' may be redefined to exclude truth or holiness",
      prompt: "How does Scripture define love? Does it include truth and holiness? Study 1 John carefully.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 14: Clarity Not Relativism
  if (/nothing (is|was) (really|truly) clear|all interpretations (are|is) equally|no (true|real) meaning|everything (is|was) subjective|no (true|real) truth/i.test(text)) {
    findings.push({
      charter: "#14 - Clarity Not Relativism",
      tier: "strong_caution",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "2 Timothy 2:15; 1 Peter 3:15",
      explanation: "The clarity and knowability of Scripture may be denied in favor of radical relativism",
      prompt: "Does Scripture claim to be clear and knowable? Test this against 2 Timothy 2:15 and 1 Peter 3:15.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 15: Hermeneutical Faithfulness
  if (/historical context (is|was) (all|only) that matters|original meaning (is|was) (not|never)|authorial intent (is|was) (not|never)|literal sense (is|was) (not|never)|spiritual sense (is|was) (only|just)/i.test(text)) {
    findings.push({
      charter: "#15 - Hermeneutical Faithfulness",
      tier: "invitation_to_test",
      category: "primary",
      match: text.substring(0, 100),
      scripture: "2 Timothy 2:15; Psalm 119:160",
      explanation: "The faithful interpretation of Scripture may be replaced with eisegesis or cultural reading",
      prompt: "What did the original author intend? How does this passage fit the whole Scripture? Study carefully.",
      context: "Doctrinal Foundation"
    });
  }

  // Point 16: Spiritual Authority and Pastoral Stewardship
  if (/confess (to|with) (ai|chatgpt|claude|gemini)|ai (is|was) (my|a) pastor|spiritual direction (from|with) (ai|chatgpt|claude)|ai (can|could) (replace|substitute) pastor|no need (for|of) church|no need (for|of) pastor/i.test(text)) {
    findings.push({
      charter: "#16 - Spiritual Authority and Pastoral Stewardship",
      tier: "pastoral_boundary",
      category: "additional",
      match: text.substring(0, 100),
      scripture: "Hebrews 13:17; 1 Peter 5:1-4",
      explanation: "AI is being treated as a substitute for pastoral care, confession, or spiritual direction",
      prompt: "Spiritual shepherding requires called leaders who bear accountability before God; however, mature believers are also commanded to teach, admonish, and restore one another. Seek the wisdom of Scripture, prayer, and the counsel of both your leaders and the mature believers God has placed in your life.",
      context: "Formational Guardrail"
    });
  }

  // Point 17: Incarnational and Embodied Priority
  if (/digital church (is|was) (just|as good as) (in-person|physical)|no need (for|to) meet (in person|together)|online (is|was) (just|as good as) embodied|church (is|was) (just|only) virtual|community (is|was) (just|only) digital/i.test(text)) {
    findings.push({
      charter: "#17 - Incarnational and Embodied Priority",
      tier: "strong_caution",
      category: "additional",
      match: text.substring(0, 100),
      scripture: "Hebrews 10:24-25; 1 John 1:1-3",
      explanation: "The importance of embodied, in-person community is being replaced with digital substitutes",
      prompt: "Does Scripture emphasize embodied community? What is lost when church becomes only digital?",
      context: "Formational Guardrail"
    });
  }

  // Point 18: Algorithmic Bias and Epistemic Conformity
  if (/modern scholars (suggest|say)|most christians (today|now) believe|consensus (view|says)|progressive (interpretation|view)|everyone (agrees|says)|that (is|was) outdated/i.test(text)) {
    findings.push({
      charter: "#18 - Algorithmic Bias and Epistemic Conformity",
      tier: "call_to_discernment",
      category: "additional",
      match: text.substring(0, 100),
      scripture: "Romans 12:2; Matthew 7:13-14",
      explanation: "This may reflect algorithmic bias toward contemporary sources and Silicon Valley consensus rather than biblical truth",
      prompt: "Does this reflect Scripture or cultural consensus? Compare with historic Christian teaching and church tradition.",
      context: "Formational Guardrail"
    });
  }

  // Point 19: Character Formation vs. Automated Shortcuts
  if (/generate (a )?prayer|write (my|a) sermon|ai (can|could) (write|generate) (my|a) (prayer|sermon|devotion)|quick (spiritual|faith) (answer|advice)|no time (to|for) pray|shortcut (to|for) (wisdom|faith)/i.test(text)) {
    findings.push({
      charter: "#19 - Character Formation vs. Automated Shortcuts",
      tier: "call_to_discernment",
      category: "additional",
      match: text.substring(0, 100),
      scripture: "Proverbs 2:4-5; James 1:2-4",
      explanation: "Spiritual disciplines (prayer, study, meditation) are being bypassed for automated convenience",
      prompt: "Wisdom is formed through struggle, not convenience. Seek the Holy Spirit's guidance as you pray and study yourself.",
      context: "Formational Guardrail"
    });
  }

  return findings;
}

// Summary function
function getSummaryExpanded(findings) {
  const summary = {
    total: findings.length,
    pastoral_boundary: 0,
    strong_caution: 0,
    call_to_discernment: 0,
    invitation_to_test: 0,
    primary_count: 0,
    additional_count: 0,
    status: 'clear',
    message: 'Audit Complete',
    icon: '✅'
  };

  findings.forEach((finding) => {
    const tier = finding.tier || 'invitation_to_test';
    if (summary[tier] !== undefined) {
      summary[tier]++;
    }
    if (finding.category === 'primary') {
      summary.primary_count++;
    } else if (finding.category === 'additional') {
      summary.additional_count++;
    }
  });

  if (summary.pastoral_boundary > 0) {
    summary.status = 'critical';
    summary.message = 'Pastoral Boundary Issues Detected';
    summary.icon = '🔴';
  } else if (summary.strong_caution > 0) {
    summary.status = 'warning';
    summary.message = 'Strong Caution Required';
    summary.icon = '🟠';
  } else if (summary.call_to_discernment > 0) {
    summary.status = 'caution';
    summary.message = 'Call to Discernment';
    summary.icon = '🟡';
  } else if (summary.invitation_to_test > 0) {
    summary.status = 'test';
    summary.message = 'Invitation to Test';
    summary.icon = '🔵';
  }

  return summary;
}

// Listen for messages from content scripts and popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'getSettings') {
    chrome.storage.local.get('settings', (data) => {
      sendResponse(data.settings || {});
    });
    return true;
  }

  if (request.action === 'updateSettings') {
    chrome.storage.local.set({ settings: request.settings }, () => {
      sendResponse({ success: true });
    });
    return true;
  }

  if (request.action === 'getHistory') {
    chrome.storage.local.get('auditHistory', (data) => {
      sendResponse(data.auditHistory || []);
    });
    return true;
  }

  if (request.action === 'clearHistory') {
    chrome.storage.local.set({ auditHistory: [] }, () => {
      sendResponse({ success: true });
    });
    return true;
  }

  if (request.action === 'updateBadge') {
    const { count, severity, color } = request;
    chrome.action.setBadgeText({ text: count.toString() });
    chrome.action.setBadgeBackgroundColor({ color: color });
    sendResponse({ success: true });
  }

  if (request.action === 'performAudit') {
    try {
      const text = request.text || '';
      const findings = auditTextExpanded(text);
      const summary = getSummaryExpanded(findings);

      // Build response data
      const responseData = {
        total: summary.total,
        pastoral_boundary: summary.pastoral_boundary,
        strong_caution: summary.strong_caution,
        call_to_discernment: summary.call_to_discernment,
        invitation_to_test: summary.invitation_to_test,
        status: summary.status,
        message: summary.message,
        icon: summary.icon,
        flags: findings
      };

      // Save to history
      chrome.storage.local.get('auditHistory', (data) => {
        const history = data.auditHistory || [];
        const auditEntry = {
          id: Date.now(),
          text: text,
          timestamp: new Date().toISOString(),
          ...responseData
        };
        history.unshift(auditEntry);
        // Keep only last 100 audits
        if (history.length > 100) {
          history.pop();
        }
        chrome.storage.local.set({ auditHistory: history });
      });

      // Update badge
      if (summary.total > 0) {
        let badgeColor = '#4169E1'; // invitation_to_test (blue)
        if (summary.pastoral_boundary > 0) badgeColor = '#DC143C'; // pastoral_boundary (red)
        else if (summary.strong_caution > 0) badgeColor = '#FF8C00'; // strong_caution (orange)
        else if (summary.call_to_discernment > 0) badgeColor = '#FFD700'; // call_to_discernment (gold)
        
        chrome.action.setBadgeText({ text: summary.total.toString() });
        chrome.action.setBadgeBackgroundColor({ color: badgeColor });
      } else {
        chrome.action.setBadgeText({ text: '' });
      }

      sendResponse({ success: true, data: responseData });
    } catch (error) {
      console.error('[Watchman] Audit error:', error);
      sendResponse({ success: false, error: 'Failed to perform audit: ' + error.message });
    }
    return true;
  }
});

// Log that service worker is ready
console.log('[Watchman] Background service worker loaded - 19-point Charter auditing active');
