const db = require('../db/models');
const { LocalAIApi } = require('../ai/LocalAIApi');

module.exports = class IntelligenceService {
  static async getExternalIntelligence() {
    // Fetch real funding opportunities from the database
    const funding_opportunities = await db.funding_opportunities.findAll();
    
    // In a real app, this would fetch from a news API or a market data provider.
    return {
      trends: [
        {
          title: "Agentic AI in Finance",
          content: "AI has moved from assistance to transactional authority, driving autonomous decision-making in risk modeling and fraud detection.",
          impact: "High",
          date: "2026-02-28"
        },
        {
          title: "Consolidation in Fintech",
          content: "Market maturation is leading to traditional banks acquiring challengers. Profitability is prioritized over 'growth at all costs'.",
          impact: "Medium",
          date: "2026-02-25"
        },
        {
          title: "Real-Time Payments Global Standard",
          content: "24/7 settlement and cross-border efficiency are now industry baselines.",
          impact: "Medium",
          date: "2026-02-20"
        }
      ],
      benchmarks: {
        saas: {
          gross_margin_target: 75,
          net_dollar_retention_median: 101,
          net_dollar_retention_top: 111,
          rule_of_40_target: 40,
          valuation_multiple_median: 6.5,
          valuation_multiple_top: 12.0
        },
        fintech: {
          cac_payback_months_target: 12,
          burn_multiplier_target: 1.5,
          ltv_cac_target: 3.5
        }
      },
      market_caps: [
        { segment: "AI-Fintech", multiple_trend: "+15%", opportunity_score: 9.2 },
        { segment: "Traditional SaaS", multiple_trend: "-5%", opportunity_score: 6.5 },
        { segment: "Infrastructure/API", multiple_trend: "+8%", opportunity_score: 8.8 }
      ],
      funding_partners: funding_opportunities,
      regulatory_updates: [
        { title: "SEC AI Disclosure Rules", content: "New requirements for disclosing AI-driven financial models.", date: "2026-01-15" },
        { title: "Global ESG Reporting Standard", content: "Mandatory ESG reporting for companies over $5M ARR.", date: "2026-02-01" }
      ]
    };
  }

  static async getProprietaryData(organizationsId) {
    if (!organizationsId) return {};

    const metrics = await db.metrics_snapshots.findAll({
      where: { organizationsId },
      order: [['as_of_at', 'DESC'], ['createdAt', 'DESC']],
      limit: 12
    });
    
    const latest = metrics[0] || {};
    
    return {
      mrr: parseFloat(latest.mrr || 0),
      arr: parseFloat(latest.arr || 0),
      margin: parseFloat(latest.gross_margin_percent || 0),
      burn: parseFloat(latest.net_burn_monthly || 0),
      runway: parseFloat(latest.runway_months || 0),
      history: metrics.map(m => ({
        date: m.as_of_at || m.createdAt,
        mrr: parseFloat(m.mrr || 0),
        burn: parseFloat(m.net_burn_monthly || 0),
        margin: parseFloat(m.gross_margin_percent || 0)
      }))
    };
  }

  static async getFinancialStewardship(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    const external = await this.getExternalIntelligence();

    const prompt = `
      Act as a Virtual CFO specializing in Financial Stewardship and Compliance.
      
      Company State:
      - ARR: $${proprietary.arr}
      - Margin: ${proprietary.margin}%
      
      Regulatory Environment (2026):
      ${JSON.stringify(external.regulatory_updates)}
      
      Tasks:
      1. **Audit Readiness**: Based on the $${proprietary.arr} ARR, suggest an audit schedule and key control areas (e.g., Revenue Recognition under ASC 606).
      2. **Closing the Books**: Provide a checklist for a 'Continuous Close' process to ensure real-time financial reporting accuracy.
      3. **Regulatory Compliance**: How do the new ${external.regulatory_updates[0].title} affect this company's AI-driven insights?
      4. **Tax Strategy**: Suggest R&D tax credit opportunities and international transfer pricing considerations if scaling globally.
      
      Format as a professional CFO report for the Board of Directors.
      IMPORTANT: This analysis is strictly for organizationsId ${organizationsId}. Data isolation is paramount.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      stewardship: LocalAIApi.extractText(aiResponse) || "Stewardship analysis unavailable."
    };
  }

  static async getCashFlowRisk(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    
    const prompt = `
      Act as a Risk Management & Cash Flow Expert (CFO role).
      
      Company Financials:
      - Monthly Burn: $${proprietary.burn}
      - Runway: ${proprietary.runway} months
      - Margin: ${proprietary.margin}%
      
      Tasks:
      1. **Liquidity Analysis**: Assess the safety of the current ${proprietary.runway}-month runway. When is the "Drop Dead Date"?
      2. **Risk Identification**: Identify top 3 financial risks (e.g., Customer Concentration, Currency Risk, or Cost Overruns).
      3. **Mitigation Strategy**: Suggest hedging or cost-cutting measures to extend runway by 25% without impacting core growth.
      4. **Profitability Path**: Build a high-level roadmap to "Default Alive" status.
      
      Be precise, data-driven, and conservative.
      IMPORTANT: This analysis is strictly for organizationsId ${organizationsId}. Data isolation is paramount.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      risk: LocalAIApi.extractText(aiResponse) || "Risk analysis unavailable."
    };
  }

  static async getCapitalStrategy(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    const external = await this.getExternalIntelligence();

    const prompt = `
      Act as a CFO & Head of Capital Markets. Your goal is to structure capital and connect with funding.
      
      Company State:
      - ARR: $${proprietary.arr}
      - Runway: ${proprietary.runway} months
      
      Available Funding Partners (2026):
      ${JSON.stringify(external.funding_partners)}
      
      Tasks:
      1. **Funding Matchmaker**: Based on the company's profile, identify the top 3 best-fit partners from the list above. Explain WHY they are a match.
      2. **Fundraising Strategy**: Structure a "Series A" or "Series B" (as appropriate) pitch focus. Should we lead with "Growth" or "Efficiency"?
      3. **Capital Structure**: Advise on 'Venture Debt' vs 'Equity' mix to minimize dilution.
      4. **Investor Relations**: Suggest a communication cadence and key KPIs to share with current stakeholders to build trust.
      
      Provide actionable, high-conviction advice.
      IMPORTANT: This analysis is strictly for organizationsId ${organizationsId}. Data isolation is paramount.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      capital: LocalAIApi.extractText(aiResponse) || "Capital strategy unavailable."
    };
  }

  static async getStrategicLeadership(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    const external = await this.getExternalIntelligence();

    const prompt = `
      Act as a Strategic CFO & Advisor to the Board.
      
      Company Context:
      - ARR: $${proprietary.arr}
      - Margin: ${proprietary.margin}%
      
      Market Trends:
      ${JSON.stringify(external.trends)}
      
      Tasks:
      1. **Digital Transformation**: How should the company leverage "Agentic AI" (Trend 1) to reduce OpEx and drive efficiency?
      2. **Business Growth Strategy**: Identify "Blue Ocean" opportunities in the fintech/SaaS space for 2026.
      3. **C-Suite Advisory**: Draft a 1-page memo for the CEO on "Navigating the 2026 Macro Environment."
      
      Be visionary, bold, and strategic.
      IMPORTANT: This analysis is strictly for organizationsId ${organizationsId}. Data isolation is paramount.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      leadership: LocalAIApi.extractText(aiResponse) || "Strategic leadership analysis unavailable."
    };
  }

  static async getESGStrategy(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    const external = await this.getExternalIntelligence();

    const prompt = `
      Act as a CFO specializing in ESG (Environmental, Social, Governance) Strategy.
      
      Regulatory Context:
      ${external.regulatory_updates[1].title}: ${external.regulatory_updates[1].content}
      
      Company Metrics:
      - ARR: $${proprietary.arr}
      
      Tasks:
      1. **ESG Framework**: Propose a realistic ESG framework that adds value to valuation rather than just being a cost.
      2. **Impact Reporting**: How can we quantify our "Social" impact for potential impact investors?
      3. **Governance Audit**: Suggest improvements to board-level oversight for AI ethics and data privacy.
      4. **Carbon Footprint Optimization**: For a SaaS company, suggest 3 high-impact areas to reduce carbon footprint.
      
      Format as a professional CFO strategy paper.
      IMPORTANT: This analysis is strictly for organizationsId ${organizationsId}. Data isolation is paramount.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      esg: LocalAIApi.extractText(aiResponse) || "ESG strategy unavailable."
    };
  }

  static async getFinancialModeling(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    const external = await this.getExternalIntelligence();

    const prompt = `
      Act as an elite Tier-1 Investment Banker. Build a sophisticated financial model for a company with the following metrics:
      
      Proprietary Financials:
      - ARR: $${proprietary.arr}
      - Gross Margin: ${proprietary.margin}%
      - Net Burn: $${proprietary.burn}/mo
      - Historical Data Points: ${proprietary.history.length} months
      
      Market Context (2026):
      - Median SaaS Multiples: ${external.benchmarks.saas.valuation_multiple_median}x
      - Top Decile Multiples: ${external.benchmarks.saas.valuation_multiple_top}x
      
      Deliver a "Modeling Pack" including:
      1. **Valuation Analysis**: Estimate Current Enterprise Value (EV) using Revenue Multiples (Base and Optimistic cases).
      2. **3-Year Projection**: Forecast ARR and Burn based on current trends.
      3. **DCF Insights**: Discuss required WACC and Terminal Value assumptions for an IPO exit in 36 months.
      4. **Capital Efficiency**: Analyze the "Burn Multiplier" and suggest optimizations for 'Rule of 40' alignment.
      
      Format as professional executive-level bullet points. 
      IMPORTANT: This analysis is strictly for organizationsId ${organizationsId}. Data isolation is paramount.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      model: LocalAIApi.extractText(aiResponse) || "Modeling unavailable."
    };
  }

  static async getMarketOpportunities(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    const external = await this.getExternalIntelligence();

    const prompt = `
      Act as a Lead M&A / Capital Markets Strategist. Analyze capitalization trends and strategic opportunities for this company.
      
      Company State:
      - ARR: $${proprietary.arr}
      - Runway: ${proprietary.runway} months
      - Margin: ${proprietary.margin}%
      
      Capitalization Trends (2026):
      ${JSON.stringify(external.market_caps)}
      
      Strategic Mandate:
      1. **Capitalization Analysis**: Which market segments have the highest multiple expansion right now? How should the company position itself?
      2. **Strategic M&A Opportunities**: Should the company be an "Acquirer" or "Target" based on its margin/runway? Suggest potential acquisition categories (e.g., vertical vs horizontal integration).
      3. **Funding Strategy**: Evaluate readiness for a 'Down-round' vs 'Flat-round' vs 'Strategic Investment' in the current 2026 climate.
      4. **Exit Planning**: Assess feasibility of IPO vs. Strategic Sale in the next 18-24 months.
      
      Be aggressive, insightful, and use investment banking terminology.
      IMPORTANT: This analysis is strictly for organizationsId ${organizationsId}. Data isolation is paramount.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      opportunities: LocalAIApi.extractText(aiResponse) || "Strategy insights unavailable."
    };
  }

  static async getIntegratedAnalysis(organizationsId) {
    const proprietary = await this.getProprietaryData(organizationsId);
    const external = await this.getExternalIntelligence();
    
    const prompt = `
      Analyze this company's proprietary data against current 2026 financial market intelligence.
      
      Proprietary Data:
      - MRR: $${proprietary.mrr}
      - Annual Recurring Revenue: $${proprietary.arr}
      - Gross Margin: ${proprietary.margin}%
      - Monthly Net Burn: $${proprietary.burn}
      - Runway: ${proprietary.runway} months
      
      External Intelligence (2026):
      - SaaS Benchmark Gross Margin: ${external.benchmarks.saas.gross_margin_target}%
      - Rule of 40 Target: 40% (Growth + Profitability)
      - Current Trend: ${external.trends[0].title} - ${external.trends[0].content}
      
      Provide a concise (3-4 bullet points) strategic analysis highlighting:
      1. How the company compares to the SaaS Gross Margin benchmark.
      2. Assessment of the Rule of 40 performance (Estimated).
      3. Strategic advice based on the "Agentic AI" trend.
      4. Risk assessment based on runway and market consolidation.
      
      IMPORTANT: This analysis is strictly for the organization with ID ${organizationsId}. 
      Ensure data isolation in your reasoning.
    `;

    const aiResponse = await LocalAIApi.createResponse({
      input: [{ role: 'user', content: prompt }]
    });

    return {
      proprietary,
      external,
      analysis: LocalAIApi.extractText(aiResponse) || "Analysis pending..."
    };
  }
};
