"""
AI Insights API Endpoints

Groq-powered financial analysis and insights for:
- Profit & Loss analysis and recommendations
- Balance Sheet health assessment and solvency analysis
- General Ledger anomaly detection and audit insights
- Sales performance analysis and dimensional trends
"""

from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.orm import Session
from typing import Dict, Any, Optional

from app.core.database import get_db
from app.core.security import get_current_user
from app.models.user import User
from app.services.groq_client import (
    analyze_profit_loss,
    analyze_balance_sheet,
    analyze_general_ledger,
    analyze_sales,
    analyze_purchases
)
from app.utils.logger import get_logger, log_exception

logger = get_logger(__name__)

router = APIRouter(prefix="/api/v1/ai", tags=["AI Insights"])


@router.post("/insights/profit-loss")
async def get_profit_loss_insights(
    pnl_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for a Profit & Loss statement.

    **Insights Include:**
    - Key financial findings and performance metrics
    - Risk flags and concerns (margins, expense trends, etc.)
    - Actionable recommendations for improvement

    **Input:** P&L report data from /dimensional-reports/profit-loss
    """
    try:
        logger.info(f"[AI] Analyzing P&L for user {current_user.id}")

        insights = analyze_profit_loss(pnl_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] P&L analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "P&L insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI P&L analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate P&L insights: {str(e)}"
        )


@router.post("/insights/balance-sheet")
async def get_balance_sheet_insights(
    bs_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for a Balance Sheet.

    **Insights Include:**
    - Financial health assessment (liquidity, solvency)
    - Debt-to-equity and equity ratio interpretation
    - Strategic recommendations for balance sheet optimization

    **Input:** Balance Sheet data from /dimensional-reports/balance-sheet
    """
    try:
        logger.info(f"[AI] Analyzing Balance Sheet for user {current_user.id}")

        insights = analyze_balance_sheet(bs_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] Balance Sheet analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "Balance Sheet insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI Balance Sheet analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate Balance Sheet insights: {str(e)}"
        )


@router.post("/insights/general-ledger")
async def get_general_ledger_insights(
    gl_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for General Ledger.

    **Insights Include:**
    - Anomaly detection (unusual transactions, patterns)
    - Account health assessment
    - Audit risk identification and control recommendations

    **Input:** General Ledger data from /dimensional-reports/general-ledger
    """
    try:
        logger.info(f"[AI] Analyzing General Ledger for user {current_user.id}")

        insights = analyze_general_ledger(gl_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] General Ledger analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "General Ledger insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI General Ledger analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate General Ledger insights: {str(e)}"
        )


@router.post("/insights/sales")
async def get_sales_insights(
    sales_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for Sales Analysis.

    **Insights Include:**
    - Sales trends and growth assessment
    - Margin health analysis
    - Top-performing dimensions and growth opportunities
    - Operational recommendations

    **Input:** Sales analysis data from /dimensional-reports/sales-analysis
    """
    try:
        logger.info(f"[AI] Analyzing Sales for user {current_user.id}")

        insights = analyze_sales(sales_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] Sales analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "Sales insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI Sales analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate Sales insights: {str(e)}"
        )


@router.post("/insights/purchases")
async def get_purchases_insights(
    purchase_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for Purchase Reports.

    **Insights Include:**
    - Supplier concentration risk assessment
    - Cost trends and efficiency observations
    - Procurement recommendations

    **Input:** Purchase report data from /purchase-reports
    """
    try:
        logger.info(f"[AI] Analyzing Purchases for user {current_user.id}")
        insights = analyze_purchases(purchase_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] Purchase analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "Purchase insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI Purchase analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate Purchase insights: {str(e)}"
        )


@router.post("/insights/inventory")
async def get_inventory_insights(
    inventory_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for Inventory Reports.

    **Insights Include:**
    - Stock health assessment (overstocking, stockouts)
    - Inventory turnover observations
    - Working capital optimization recommendations

    **Input:** Inventory report data
    """
    try:
        logger.info(f"[AI] Analyzing Inventory for user {current_user.id}")
        from app.services.groq_client import analyze_inventory

        insights = analyze_inventory(inventory_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] Inventory analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "Inventory insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI Inventory analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate Inventory insights: {str(e)}"
        )


@router.post("/insights/cogs")
async def get_cogs_insights(
    cogs_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for COGS Reports.

    **Insights Include:**
    - Cost structure assessment
    - Gross margin health check
    - Cost reduction opportunities

    **Input:** COGS report data
    """
    try:
        logger.info(f"[AI] Analyzing COGS for user {current_user.id}")
        from app.services.groq_client import analyze_cogs

        insights = analyze_cogs(cogs_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] COGS analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "COGS insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI COGS analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate COGS insights: {str(e)}"
        )


@router.post("/insights/banking")
async def get_banking_insights(
    banking_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for Banking Reports.

    **Insights Include:**
    - Cash position assessment
    - Liquidity observations
    - Cash management recommendations

    **Input:** Banking report data
    """
    try:
        logger.info(f"[AI] Analyzing Banking for user {current_user.id}")
        from app.services.groq_client import analyze_banking

        insights = analyze_banking(banking_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] Banking analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "Banking insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI Banking analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate Banking insights: {str(e)}"
        )


@router.post("/insights/vat")
async def get_vat_insights(
    vat_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Generate AI-powered insights for VAT Reports.

    **Insights Include:**
    - VAT position assessment
    - Compliance observations
    - Filing and audit recommendations

    **Input:** VAT report data
    """
    try:
        logger.info(f"[AI] Analyzing VAT for user {current_user.id}")
        from app.services.groq_client import analyze_vat

        insights = analyze_vat(vat_data)

        if not insights:
            return {
                "status": "warning",
                "data": None,
                "message": "AI insights not available (Groq API not configured)"
            }

        logger.info(f"[AI] VAT analysis completed")
        return {
            "status": "success",
            "data": insights,
            "message": "VAT insights generated successfully"
        }

    except Exception as e:
        log_exception(e, "AI VAT analysis failed")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate VAT insights: {str(e)}"
        )


@router.get("/health")
async def ai_health_check():
    """Health check for AI Insights API"""
    return {
        "status": "success",
        "message": "AI Insights API is operational",
        "features": [
            "Profit & Loss Analysis",
            "Balance Sheet Assessment",
            "General Ledger Auditing",
            "Sales Performance Analysis",
            "Purchase Analytics",
            "Inventory Management",
            "COGS Analysis",
            "Banking & Treasury",
            "VAT Compliance"
        ],
        "models": [
            "llama-3.1-70b-versatile (deep analysis)",
            "llama-3.1-8b-instant (fast summaries)",
            "mixtral-8x22b (complex reasoning)"
        ]
    }
