from datetime import datetime
from pymongo.errors import DuplicateKeyError
from app.db import database
from bson import ObjectId
from typing import Optional
from app.v1.models.platform.workforcevehicle import VehicleAssignment

COLLECTION_NAME = "workforce_vehicle"
FLEET_COLLECTION_NAME = "fleets"
WORKFORCE_COLLECTION_NAME = "workforce"

def create_vehicle_assignment_service(data: VehicleAssignment, db: database.MongoDB) -> dict:
    collection = db[COLLECTION_NAME]
    assignment_data = data.dict()
    assignment_data["created_date"] = datetime.utcnow()
    assignment_data["updated_date"] = datetime.utcnow()

    try:
        result = collection.insert_one(assignment_data)
        assignment_data["_id"] = str(result.inserted_id)

        #Maintain Assigned details in fleets collection
        # Update the fleets collection
        fleets_collection = db[FLEET_COLLECTION_NAME]
        fleets_collection.update_one(
            {"_id": ObjectId(data.vehicle_id)},
            {
                "$set": {
                    "is_fleet_assigned": True,
                    "assigned_from": data.assigned_from,
                    "assigned_to": data.assigned_to,
                    "fleet_info": {
                        "is_fleet_assigned": True,
                        "assigned_from": data.assigned_from,
                        "assigned_to": data.assigned_to,
                        "status": data.status
                    }
                }
            }
        )

        workforce_collection = db[WORKFORCE_COLLECTION_NAME]
        workforce_update_result = workforce_collection.update_one(
            {"_id": ObjectId(data.workforce_id)},
            {
                "$set": {
                    "is_fleet_assigned": True,
                    "assigned_from": data.assigned_from,
                    "assigned_to": data.assigned_to,
                    "fleet_info": {
                        "is_fleet_assigned": True,
                        "assigned_from": data.assigned_from,
                        "assigned_to": data.assigned_to,
                        "status": data.status
                    }
                }
            }
        )

        # if fleets_update_result.modified_count == 0:
        #     print(f"Warning: No fleet document updated for _id = {data.vehicle_id}")

        return assignment_data
    except DuplicateKeyError:
        raise ValueError("Vehicle is already assigned to this workforce.")

def get_vehicle_assignments_service(account_id: str, workforce_id: Optional[str], fleet_id: Optional[str], db: database.MongoDB) -> list:
    collection = db[COLLECTION_NAME]
    query = {"account_id": account_id}

    if workforce_id:
        query["workforce_id"] = workforce_id
    if vehicle_id:
        query["vehicle_id"] = vehicle_id

    records = list(collection.find(query))
    for r in records:
        r["_id"] = str(r["_id"])
        if "assigned_from" in r and isinstance(r["assigned_from"], datetime):
            r["assigned_from"] = r["assigned_from"].isoformat()
        if "assigned_to" in r and isinstance(r["assigned_to"], datetime):
            r["assigned_to"] = r["assigned_to"].isoformat()
        if "created_date" in r and isinstance(r["created_date"], datetime):
            r["created_date"] = r["created_date"].isoformat()
        if "updated_date" in r and isinstance(r["updated_date"], datetime):
            r["updated_date"] = r["updated_date"].isoformat()

    return records

def unassign_vehicle_service(workforce_id: str, db: database.MongoDB) -> dict:
    collection = db[COLLECTION_NAME]
    
    # Find active assignment
    assignment = collection.find_one({
        "workforce_id": workforce_id,
        "status": True
    })
    
    if not assignment:
        raise HTTPException(status_code=404, detail="No active assignment found for this workforce.")

    # Update the assignment
    update_result = collection.update_one(
        {"_id": assignment["_id"]},
        {
            "$set": {
                "assigned_to": datetime.utcnow(),
                "status": False,
                "updated_date": datetime.utcnow()
            }
        }
    )

    if update_result.modified_count == 0:
        raise HTTPException(status_code=500, detail="Unassignment failed.")

    assignment["assigned_to"] = datetime.utcnow()
    assignment["status"] = False
    return {
        "message": "Vehicle unassigned successfully.",
        "assignment": {
            "workforce_id": assignment["workforce_id"],
            "vehicle_id": assignment["vehicle_id"],
            "status": False,
            "assigned_to": assignment["assigned_to"]
        }
    }