from datetime import datetime
from pymongo.collection import Collection, ReturnDocument
from app.db import database
from app.v1.models.cx.crm import Comment, AccountDetail, SalesStatus, AccountStats, Log
from app.v1.libraries.object import str_to_objectid
from typing import Optional, List, Dict, Any

# -----------------------------
# COMMENTS SERVICES
# -----------------------------
def add_comment_service(account_id: str, team_member_id: str, comment_text: str, db: database.MongoDB) -> dict:
    comments_collection: Collection = db["crm_comments"]
    comment_data = Comment(account_id=account_id, team_member_id=team_member_id, comment=comment_text).dict()
    result = comments_collection.insert_one(comment_data)
    comment_data["_id"] = str(result.inserted_id)
    return comment_data

def delete_comment_service(comment_id: str, db: database.MongoDB) -> dict:
    comments_collection: Collection = db["crm_comments"]
    comment = comments_collection.find_one({"_id": str_to_objectid(comment_id)})
    if not comment:
        raise ValueError("Comment not found")
    comments_collection.delete_one({"_id": str_to_objectid(comment_id)})
    comment["_id"] = str(comment["_id"])
    return comment

def get_comments_service(account_id: str, skip: int, limit: int, db: database.MongoDB) -> List[dict]:
    comments_collection: Collection = db["crm_comments"]
    cursor = comments_collection.find({"account_id": account_id}).sort("created_date", -1).skip(skip).limit(limit)
    comments = []
    for comment in cursor:
        comment["_id"] = str(comment["_id"])
        comments.append(comment)
    return comments

# -----------------------------
# ACCOUNT DETAIL & SALES PIPELINE SERVICES
# -----------------------------
def get_account_detail_service(account_id: str, db: database.MongoDB) -> Optional[dict]:
    details_collection: Collection = db["account_details"]
    detail = details_collection.find_one({"account_id": account_id})
    if detail:
        detail["_id"] = str(detail["_id"])
    return detail

def update_account_detail_service(account_id: str, update_data: Dict[str, Any], db: database.MongoDB) -> dict:
    details_collection: Collection = db["account_details"]
    update_data["updated_date"] = datetime.utcnow()
    result = details_collection.find_one_and_update(
        {"account_id": account_id},
        {"$set": update_data},
        upsert=True,
        return_document=ReturnDocument.AFTER
    )
    result["_id"] = str(result["_id"])
    return result

def update_sales_pipeline_service(account_id: str, pipeline: List[Dict[str, Any]], db: database.MongoDB) -> dict:
    if len(pipeline) > 5:
        raise ValueError("Sales pipeline cannot have more than 5 statuses.")
    details_collection: Collection = db["account_details"]
    update_data = {"sales_pipeline": pipeline, "updated_date": datetime.utcnow()}
    result = details_collection.find_one_and_update(
        {"account_id": account_id},
        {"$set": update_data},
        upsert=True,
        return_document=ReturnDocument.AFTER
    )
    result["_id"] = str(result["_id"])
    return result

# -----------------------------
# ACCOUNT STATS SERVICES
# -----------------------------
def get_account_stats_service(account_id: str, db: database.MongoDB, skip: int, limit: int) -> dict:
    # Comments aggregation
    comments_collection: Collection = db["crm_comments"]
    total_comments = comments_collection.count_documents({"account_id": account_id})
    last_comment_cursor = comments_collection.find({"account_id": account_id}).sort("created_date", -1).limit(1)
    last_comment_date = None
    for comment in last_comment_cursor:
        last_comment_date = comment.get("created_date")
    
    # Users count from users collection (assuming field "account_id")
    users_collection = db["users"]
    total_users = users_collection.count_documents({"account_id": account_id})
    
    # Get current sales status from account_details sales pipeline
    details_collection = db["account_details"]
    account_detail = details_collection.find_one({"account_id": account_id})
    current_sales_status = None
    if account_detail and "sales_pipeline" in account_detail and account_detail["sales_pipeline"]:
        current_sales_status = account_detail["sales_pipeline"][-1].get("status")
    
    monthly_payments = 0.0  # Dummy value; replace with actual logic if available.
    
    stats = {
        "total_comments": total_comments,
        "last_comment_date": last_comment_date.isoformat() if last_comment_date else None,
        "total_users": total_users,
        "monthly_payments": monthly_payments,
        "current_sales_status": current_sales_status
    }
    return stats

# -----------------------------
# LOGS SERVICES
# -----------------------------
def get_logs_service(account_id: str, skip: int, limit: int, db: database.MongoDB) -> List[dict]:
    logs_collection: Collection = db["crm_logs"]
    cursor = logs_collection.find({"account_id": account_id}).sort("timestamp", -1).skip(skip).limit(limit)
    logs = []
    for log in cursor:
        log["_id"] = str(log["_id"])
        logs.append(log)
    return logs
