"""
Groq AI Client for Financial Analysis & Insights

Integrates Groq's fast LLM models for:
- Financial report analysis and insights
- Anomaly detection and risk flagging
- Narrative summaries and recommendations
- Code/schema analysis for technical queries
"""

import os
import json
from typing import Dict, Any, Optional

try:
    from groq import Groq
except ImportError:
    Groq = None  # type: ignore[misc, assignment]

from app.utils.logger import get_logger

logger = get_logger(__name__)

# Initialize Groq client
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
if not GROQ_API_KEY:
    logger.warning("GROQ_API_KEY not configured. AI insights will not be available.")
elif Groq is None:
    logger.warning("groq package not installed. AI insights will not be available.")

groq_client = Groq(api_key=GROQ_API_KEY) if (GROQ_API_KEY and Groq) else None


def run_groq(
    prompt: str,
    model: str = "llama-3.1-70b-versatile",
    temperature: float = 0.2,
    max_tokens: int = 1200
) -> Optional[str]:
    """
    Execute a prompt via Groq API.

    Args:
        prompt: The user/system prompt
        model: Groq model name
        temperature: 0.0-2.0; lower = deterministic, higher = creative
        max_tokens: Max response length

    Returns:
        Response text or None if not configured
    """
    if not groq_client:
        logger.warning("Groq client not initialized. Skipping AI insights.")
        return None

    try:
        response = groq_client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            temperature=temperature,
            max_tokens=max_tokens,
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        logger.error(f"Groq API error: {str(e)}")
        return None


def analyze_profit_loss(pnl_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze Profit & Loss statement and return insights.

    Args:
        pnl_data: P&L report data from dimensional_reports_service

    Returns:
        Dict with insights, risks, and recommendations
    """
    if not groq_client:
        return None

    # Build a concise prompt with key P&L metrics
    total_revenue = pnl_data.get("revenue", {}).get("total", 0)
    total_expenses = pnl_data.get("expenses", {}).get("total", 0)
    net_income = pnl_data.get("net_income", 0)
    period = pnl_data.get("period", {})

    prompt = f"""You are a financial analyst. Analyze this P&L statement and provide:
1. Key insights (2-3 findings)
2. Risk flags or concerns (if any)
3. Actionable recommendations (2-3 items)

Period: {period.get('start_date', 'N/A')} to {period.get('end_date', 'N/A')}
Total Revenue: ${total_revenue:,.2f}
Total Expenses: ${total_expenses:,.2f}
Net Income: ${net_income:,.2f}
Net Margin: {(net_income/total_revenue*100) if total_revenue > 0 else 0:.1f}%

Dimensional breakdown available:
{json.dumps(pnl_data.get('dimensional_breakdown', [])[:3], indent=2)}

Provide concise, actionable insights. Be direct. Avoid jargon."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {
            "report_type": "profit_loss",
            "insights": response,
            "status": "success"
        }
    return None


def analyze_balance_sheet(bs_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze Balance Sheet and return insights.

    Args:
        bs_data: Balance Sheet report data

    Returns:
        Dict with financial health assessment, liquidity analysis, solvency ratio interpretation
    """
    if not groq_client:
        return None

    total_assets = bs_data.get("assets", {}).get("total", 0)
    total_liabilities = bs_data.get("liabilities", {}).get("total", 0)
    total_equity = bs_data.get("equity", {}).get("total", 0)
    as_of_date = bs_data.get("as_of_date", "N/A")

    # Calculate key ratios
    debt_to_equity = (total_liabilities / total_equity) if total_equity > 0 else 0
    equity_ratio = (total_equity / total_assets) if total_assets > 0 else 0

    prompt = f"""You are a financial analyst. Assess this Balance Sheet and provide:
1. Financial health assessment (strong/stable/at-risk)
2. Liquidity observations
3. Solvency concerns or strengths
4. Top recommendations

As of: {as_of_date}
Total Assets: ${total_assets:,.2f}
Total Liabilities: ${total_liabilities:,.2f}
Total Equity: ${total_equity:,.2f}

Key Ratios:
- Debt-to-Equity: {debt_to_equity:.2f}
- Equity Ratio: {equity_ratio:.1%}

Major asset categories: {', '.join(list(bs_data.get('assets', {}).get('categories', {}).keys())[:3])}
Major liability categories: {', '.join(list(bs_data.get('liabilities', {}).get('categories', {}).keys())[:3])}

Provide concise financial assessment. Highlight material issues or strengths."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {
            "report_type": "balance_sheet",
            "insights": response,
            "status": "success"
        }
    return None


def analyze_general_ledger(gl_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze General Ledger transactions for anomalies and trends.

    Args:
        gl_data: General Ledger report data

    Returns:
        Dict with anomaly flags, account health assessment, audit considerations
    """
    if not groq_client:
        return None

    accounts = gl_data.get("accounts", {})
    period = gl_data.get("period", {})

    # Sample top 5 accounts by activity
    account_summary = {}
    for code, acc_data in list(accounts.items())[:5]:
        entries = acc_data.get("entries", [])
        total_debits = acc_data.get("total_debits", 0)
        total_credits = acc_data.get("total_credits", 0)
        account_summary[code] = {
            "name": acc_data.get("name", "Unknown"),
            "type": acc_data.get("account_type", "Unknown"),
            "entry_count": len(entries),
            "total_debits": total_debits,
            "total_credits": total_credits,
            "balance": acc_data.get("running_balance", 0)
        }

    prompt = f"""You are a financial auditor. Review this GL summary and identify:
1. Any unusual patterns or anomalies (large transactions, rare entry types, etc.)
2. Accounts that may need attention or reconciliation
3. Audit or control risk areas
4. Recommendations for GL cleanliness/integrity

Period: {period.get('start_date', 'N/A')} to {period.get('end_date', 'N/A')}
Total accounts reviewed: {len(accounts)}

Sample accounts:
{json.dumps(account_summary, indent=2, default=str)}

Focus on practical audit risks. Be direct."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {
            "report_type": "general_ledger",
            "insights": response,
            "status": "success"
        }
    return None


def analyze_sales(sales_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze Sales report for trends, profitability, and dimensional performance.

    Args:
        sales_data: Sales analysis report data

    Returns:
        Dict with sales trends, margin analysis, dimensional performance insights
    """
    if not groq_client:
        return None

    total_sales = sales_data.get("total_sales", 0)
    period = sales_data.get("period", {})
    category_sales = sales_data.get("category_sales", {})
    dimensional_breakdown = sales_data.get("dimensional_breakdown", [])

    # Top dimensional performers
    top_dims = sorted(
        dimensional_breakdown,
        key=lambda x: x.get("revenue", 0),
        reverse=True
    )[:3]

    prompt = f"""You are a sales analyst. Analyze this sales performance and provide:
1. Sales trend and growth assessment
2. Margin health analysis (gross profit trends)
3. Top performing dimensions/segments
4. Operational recommendations

Period: {period.get('start_date', 'N/A')} to {period.get('end_date', 'N/A')}
Total Revenue: ${total_sales:,.2f}
Top Categories: {', '.join(list(category_sales.keys())[:3])}

Top Dimensional Performers (by revenue):
{json.dumps(top_dims, indent=2, default=str)}

Provide sales-focused insights. Highlight growth opportunities and margin risks."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {
            "report_type": "sales_analysis",
            "insights": response,
            "status": "success"
        }
    return None


def analyze_purchases(purchase_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze Purchase Report for supplier performance and cost trends.
    """
    if not groq_client:
        return None

    total_amount = purchase_data.get("total_amount", 0)
    purchase_count = purchase_data.get("purchase_count", 0)
    avg_purchase = purchase_data.get("average_purchase", 0)
    top_supplier = purchase_data.get("top_supplier", "Unknown")
    period = purchase_data.get("period", {})

    prompt = f"""You are a procurement analyst. Analyze purchases and provide:
1. Supplier concentration risk assessment
2. Cost trends and efficiency observations
3. Procurement recommendations

Period: {period.get('start', 'N/A')} to {period.get('end', 'N/A')}
Total Purchases: ${total_amount:,.2f}
Count: {purchase_count} transactions
Average: ${avg_purchase:,.2f}
Top Supplier: {top_supplier}

Focus on cost control and supplier diversification."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {"report_type": "purchases", "insights": response, "status": "success"}
    return None


def analyze_inventory(inventory_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze Inventory Report for stock levels and turnover.
    """
    if not groq_client:
        return None

    total_value = inventory_data.get("total_value", 0)
    item_count = inventory_data.get("item_count", 0)
    low_stock = inventory_data.get("low_stock_count", 0)
    overstock = inventory_data.get("overstock_count", 0)

    prompt = f"""You are an inventory manager. Analyze inventory and provide:
1. Stock health assessment (overstocking, stockouts)
2. Inventory turnover observations
3. Working capital optimization recommendations

Total Inventory Value: ${total_value:,.2f}
Items: {item_count}
Low Stock Items: {low_stock}
Overstock Items: {overstock}

Focus on inventory optimization."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {"report_type": "inventory", "insights": response, "status": "success"}
    return None


def analyze_cogs(cogs_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze COGS Report for cost structure and margin trends.
    """
    if not groq_client:
        return None

    total_cogs = cogs_data.get("total_cogs", 0)
    total_revenue = cogs_data.get("total_revenue", 0)
    gross_margin = ((total_revenue - total_cogs) / total_revenue * 100) if total_revenue > 0 else 0

    prompt = f"""You are a cost accountant. Analyze COGS and provide:
1. Cost structure assessment
2. Gross margin health check
3. Cost reduction opportunities

Total COGS: ${total_cogs:,.2f}
Total Revenue: ${total_revenue:,.2f}
Gross Margin: {gross_margin:.1f}%

Focus on margin improvement."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {"report_type": "cogs", "insights": response, "status": "success"}
    return None


def analyze_banking(banking_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze Banking Report for cash flow and liquidity.
    """
    if not groq_client:
        return None

    total_balance = banking_data.get("total_balance", 0)
    account_count = banking_data.get("account_count", 0)
    cash_in = banking_data.get("total_inflows", 0)
    cash_out = banking_data.get("total_outflows", 0)

    prompt = f"""You are a treasury analyst. Analyze banking and provide:
1. Cash position assessment
2. Liquidity observations
3. Cash management recommendations

Total Bank Balance: ${total_balance:,.2f}
Accounts: {account_count}
Period Inflows: ${cash_in:,.2f}
Period Outflows: ${cash_out:,.2f}
Net Change: ${cash_in - cash_out:,.2f}

Focus on liquidity and cash optimization."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {"report_type": "banking", "insights": response, "status": "success"}
    return None


def analyze_vat(vat_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze VAT Report for compliance and filing accuracy.
    """
    if not groq_client:
        return None

    vat_payable = vat_data.get("vat_payable", 0)
    vat_receivable = vat_data.get("vat_receivable", 0)
    net_vat = vat_payable - vat_receivable

    prompt = f"""You are a tax compliance analyst. Analyze VAT and provide:
1. VAT position assessment
2. Compliance observations
3. Filing and audit recommendations

VAT Payable (Output): ${vat_payable:,.2f}
VAT Receivable (Input): ${vat_receivable:,.2f}
Net VAT: ${net_vat:,.2f} {'(payable)' if net_vat > 0 else '(refund due)'}

Focus on compliance and accuracy."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {"report_type": "vat", "insights": response, "status": "success"}
    return None


def analyze_purchases(purchase_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Analyze Purchase Report for supplier performance and cost trends.
    """
    if not groq_client:
        return None

    total_amount = purchase_data.get("total_purchases", purchase_data.get("total_amount", 0))
    purchase_count = purchase_data.get("purchase_count", len(purchase_data.get("period_purchases", {})))
    avg_purchase = purchase_data.get("average_purchase", 0)
    top_dimension = None
    breakdown = purchase_data.get("dimensional_breakdown", [])
    if breakdown:
        top_dimension = breakdown[0].get("dimension_value")

    prompt = f"""You are a procurement analyst. Analyze purchases and provide:
1. Supplier or category concentration risk (highlight top dependency)
2. Cost trends and efficiency observations
3. Procurement recommendations

Total Purchases: ${total_amount:,.2f}
Transactions (estimated): {purchase_count}
Average Purchase: ${avg_purchase:,.2f}
Top Dimension: {top_dimension or 'N/A'}

Focus on cost control, diversification, and quick wins."""

    response = run_groq(prompt, temperature=0.15, max_tokens=800)
    if response:
        return {"report_type": "purchases", "insights": response, "status": "success"}
    return None


def extract_summary(
    text: str,
    max_points: int = 3
) -> Optional[str]:
    """
    Extract and summarize key points from text (for distillation/training).

    Args:
        text: Long-form text to summarize
        max_points: Max bullet points to extract

    Returns:
        Bullet-point summary
    """
    if not groq_client:
        return None

    prompt = f"""Extract {max_points} key takeaways as concise bullet points. No intro text.

Text:
{text}"""

    return run_groq(prompt, model="llama-3.1-8b-instant", temperature=0.1, max_tokens=300)
