from .init_repo import workspace_keys_col, subscription_col, call_col
from .chatutilities import (
    get_store_id_from_agent,
    get_store_credentials,
    save_message,
)
from ..AnalyzerAgent.user_facts_analyzer import process_chat_every_interval
from .chatschemas import AgentRequest
from .agent_cache import get_sales_agent
from ..logger import log
import time
from typing import Dict, Any
import asyncio
from bson import ObjectId
from pymongo import ReturnDocument

async def _persist_ai_response(data, response, chat_id):
    """Background task: save conversation and process intervals."""
    try:
        save_message("user", data.text, chat_id)

        ai_response = (response or {}).get("data", {}).get("ai_response", {}) or {}
        save_message("ai", ai_response, chat_id)
        process_chat_every_interval(chat_id)

    except Exception as e:
        log.error(f"Error saving conversation transcript: {e}")


def validate_workspace_and_subscription(secret_key: str) -> None:
    """
    Validate workspace and subscription based on secret key.
    Raises ValueError if invalid or subscription limit exceeded.
    """
    workspace = workspace_keys_col.find_one(
        {"key": secret_key.lower(), "is_delete": False}
    )
    if not workspace:
        raise ValueError("Invalid secret key")

    subscription = subscription_col.find_one(
        {"workspace_id": workspace["workspace_id"], "is_active": True},
        {"chat_token_limit_left": 1},  # optional: only fetch needed field
    )
    if not subscription or subscription.get("chat_token_limit_left", 0) <= 0:
        raise ValueError("No active subscription or token limit reached")

def deduct_chat_limit(workspace_id):
    """Try to decrement chat token silently; never raise, never return anything."""
    try:
        subscription_col.update_one(
            {
                "workspace_id": ObjectId(workspace_id),
                "chat_token_limit_left": {"$gt": 0},
            },
            {"$inc": {"chat_token_limit_left": -1}},
        )
    except Exception:
        # silently ignore anything
        pass

    
# def deduct_chat_limit(workspace_id) -> None:
#     """
#     Deduct 1 chat from active subscription.
#     Raises exception if limit exceeded or no active subscription.
#     """

#     now_ts = int(time.time())

#     subscription = subscription_col.find_one_and_update(
#         {
#             "workspace_id": ObjectId(workspace_id),
#             # "status": {"$in": ["authenticated", "active"]},
#             "end_date": {"$gt": now_ts},
#             "chat_token_limit_left": {"$gt": 0},
#         },
#         {
#             "$inc": {"chat_token_limit_left": -1},
#         },
#         return_document=ReturnDocument.AFTER,
#     )

#     if not subscription:
#         raise Exception("Chat limit exceeded or subscription expired")

#     return {
#         "remaining": subscription["chat_token_limit_left"]
#     }


def _create_or_update_chat(data: AgentRequest, user_id: str) -> str:
    """Create a new chat if chat_id not provided, else update the last_message."""
    try:
        if not data.chat_id:
            # workspace = workspace_keys_col.find_one(
            #     {"key": data.secret_key.lower(), "is_delete": False}
            # )
            # deduct_chat_limit(workspace["workspace_id"])
            chat_doc = call_col.insert_one(
                {
                    "type": "CHAT",
                    "last_message": data.text,
                    "created_at": int(time.time() * 1000),
                    "status": "ACTIVE",
                    "user_id": user_id,
                    "name": data.user_name or "Guest",
                    "email": data.user_email or "",
                }
            )
            return str(chat_doc.inserted_id)
        else:
            chat_id = data.chat_id
            call_col.update_one(
                {"_id": ObjectId(chat_id)}, {"$set": {"last_message": data.text}}
            )
            return chat_id
    except Exception as e:
        raise Exception("Error creating/updating chat session", str(e))


async def chat_with_ai(data: AgentRequest, user_id: str) -> Dict[str, Any]:
    """Main entrypoint: validates request, manages session, and routes to AI agent."""
    # Validate workspace and subscription
    # validate_workspace_and_subscription(data.secret_key)
    # Chat Session (create/update)
    chat_id = _create_or_update_chat(data, user_id)
    if not chat_id:
        log.warning("No chat_id provided, response")
        return

    # ---------------------------------------------------------
    # Integrations
    # ---------------------------------------------------------
    store_id = get_store_id_from_agent(user_id)
    if not store_id:
        log.warning("No store_id provided, skipping credentials fetch")

    shopify_creds = get_store_credentials(store_id) if store_id else None
    sales_agent = get_sales_agent(chat_id, store_id)
    # ---------------------------------------------------------
    # AI Response
    # ---------------------------------------------------------
    response = await sales_agent.chat_with_ai_supervisor(
        AgentRequest(
            text=data.text,
            chat_id=chat_id,
            user_id=user_id,
            user_name=data.user_name,
            user_email=data.user_email,
            shopify_creds=shopify_creds,
        ),
        user_id=user_id,
    )

    # ---------------------------------------------------------
    # Persistence
    # ---------------------------------------------------------
    if data.type == "AIAgent":
        asyncio.create_task(_persist_ai_response(data, response, chat_id))

    return response
