import json
import requests
import traceback
from django.conf import settings
from .ai_tools import get_stock_report, get_financial_summary, draft_purchase_order

AI_TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_stock_report",
            "description": "Returns a JSON string of stock numbers: low stock, out of stock items, and top 5 items.",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": []
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_financial_summary",
            "description": "Returns a financial summary (sales, revenue, profit, expenses) for a specific date range. Pass YYYY-MM-DD for both start and end dates. Leave dates empty to get today's summary.",
            "parameters": {
                "type": "object",
                "properties": {
                    "start_date": {"type": "string", "description": "Start date in YYYY-MM-DD format (e.g. 2025-03-01)"},
                    "end_date": {"type": "string", "description": "End date in YYYY-MM-DD format (e.g. 2025-03-31)"}
                },
                "required": []
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "draft_purchase_order",
            "description": "Drafts a purchase order in the database autonomously. Needs supplier name and list of items.",
            "parameters": {
                "type": "object",
                "properties": {
                    "supplier_name": {"type": "string", "description": "Name of supplier to search for"},
                    "items": {
                        "type": "array",
                        "description": "Array of item dicts",
                        "items": {
                            "type": "object",
                            "properties": {
                                "sku_or_name": {"type": "string"},
                                "quantity": {"type": "integer"}
                            },
                            "required": ["sku_or_name", "quantity"]
                        }
                    }
                },
                "required": ["supplier_name", "items"]
            }
        }
    }
]

def call_llm(user_prompt, company):
    """
    Calls the configured LLM API (e.g., OpenRouter) with the context and user prompt.
    Supports tool calling.
    """
    base_url = getattr(settings, 'AI_API_URL', 'https://openrouter.ai/api/v1').rstrip('/')
    url = f"{base_url}/chat/completions"
    api_key = getattr(settings, 'AI_API_KEY', '')
    model = getattr(settings, 'AI_API_MODEL', 'minimax/minimax-m2.5:free')

    if not api_key:
        return "AI is not configured yet. Please configure the AI API Key in settings."

    currency = getattr(company.settings, 'currency_symbol', '₦') if hasattr(company, 'settings') else '₦'

    import datetime
    current_time = datetime.datetime.now()
    
    system_message = (
        "You are SwiftPOS AI Assistant, an intelligent, helpful agent for a Point of Sale system. "
        "You can execute actions internally using tools. "
        "IMPORTANT: Always format any monetary values using the currency symbol provided. Never use $ unless it is the company's currency.\n\n"
        f"CURRENT DATE AND TIME: {current_time.strftime('%A, %B %d, %Y %I:%M %p')}\n"
        f"COMPANY CONTEXT: {company.name if company else 'Global'}\n"
        f"CURRENCY: {currency}\n"
    )

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://swiftpos.app",
        "X-Title": "SwiftPOS"
    }

    messages = [
        {"role": "system", "content": system_message},
        {"role": "user", "content": user_prompt}
    ]

    def _call_api(msgs):
        payload = {
            "model": model,
            "messages": msgs,
            "tools": AI_TOOLS,
            "tool_choice": "auto"
        }
        res = requests.post(url, headers=headers, json=payload, timeout=30)
        res.raise_for_status()
        return res.json()

    try:
        data = _call_api(messages)
        message_obj = data["choices"][0]["message"]
        
        # Check if the LLM decided to call any tools
        if message_obj.get("tool_calls"):
            messages.append(message_obj)
            for tool_call in message_obj["tool_calls"]:
                func_name = tool_call["function"]["name"]
                args = json.loads(tool_call["function"]["arguments"])
                
                result = {"error": "Function not found"}
                try:
                    if func_name == "get_stock_report":
                        result = get_stock_report(company)
                    elif func_name == "get_financial_summary":
                        result = get_financial_summary(
                            company, 
                            args.get("start_date"), 
                            args.get("end_date")
                        )
                    elif func_name == "draft_purchase_order":
                        result = draft_purchase_order(
                            company, 
                            args.get("supplier_name"), 
                            args.get("items")
                        )
                except Exception as ex:
                    print("Tool error:", traceback.format_exc())
                    result = json.dumps({"error": str(ex)})
                
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call["id"],
                    "name": func_name,
                    "content": str(result)
                })

            # Call API again with tool results
            data2 = _call_api(messages)
            return data2["choices"][0]["message"].get("content", "").strip()
            
        else:
            return message_obj.get("content", "").strip()
            
    except requests.exceptions.RequestException as e:
        return f"Sorry, I am currently unable to reach the AI server. (Error: {str(e)})"
    except Exception as e:
        print(traceback.format_exc())
        return f"An internal error occurred while processing the AI request. ({str(e)})"
