import os
from fastapi import APIRouter, Depends, HTTPException, Query,Form,File,UploadFile
from fastapi.responses import JSONResponse
from typing import Optional, List, Dict, Any
from datetime import datetime,date
from bson import ObjectId
import re
from pathlib import Path

from app.db import database
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.models.platform.fleets import (
    Fleet,
    FleetBase,
    FleetCreate,
    FleetResponseList,
    FleetUpdate,
    VehicleBase
)
from app.v1.services.platform.fleets import (
    create_fleet_service,
    get_fleets_service,
    read_fleet_service,
    update_fleet_service,
    delete_fleet_service,
    get_fleet_vehicles_service
)

router = APIRouter()

# @router.post("/", response_model=Fleet)
# async def create_fleet_endpoint(
#     fleet: FleetCreate,
#     db: database.MongoDB = Depends(database.get_mongo_db),
#     current_user: dict = Depends(get_current_userdetails)
# ):
#     fleet_data = fleet.model_dump()
#     fleet_data["account_id"] = current_user.get("account_id", "")
#     fleet_data["user_id"] = current_user.get("user_id", "")

#     result = create_fleet_service(fleet_data, db)
#     return JSONResponse(
#         content={"message": "Fleet created successfully", "fleet": result["fleet_data"]},
#         status_code=201
#     )

@router.post("/", response_model=Fleet)
async def create_fleet_endpoint(
    fleet_name: str = Form(...),
    description: Optional[str] = Form(None),
    status: str = Form(...),
    vehicle_id: Optional[str] = Form(None),
    registration_number: Optional[str] = Form(None),
    vin_number: Optional[str] = Form(None),
    vehicle_model_id: Optional[str] = Form(None),
    color: Optional[str] = Form(None),
    year: Optional[int] = Form(None),
    vehicle_image: UploadFile = File(None),
    insurance_number: Optional[str] = Form(None),
    insurance_expiry: Optional[date] = Form(None),
    vendor_id: Optional[str] = Form(None),
    dealer_id: Optional[str] = Form(None),
    fuel_type: Optional[str] = Form(None),
    vehicle_type: Optional[str] = Form(None),
    capacity: Optional[str] = Form(None),
    vendor_name: str = Form(...),
    tag_name: Optional[str] = Form(None),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails),    
):
    FLEET_IMG_PATH = Path("public/fleets")
    FLEET_IMG_PATH.mkdir(parents=True, exist_ok=True)

    image_filename = None
    if vehicle_image and vehicle_image.filename:
        timestamp = int(datetime.now().timestamp())
        ext = vehicle_image.filename.split('.')[-1]
        image_filename = f"fleet-{timestamp}.{ext}"
        filepath = FLEET_IMG_PATH / image_filename
        with open(filepath, "wb") as f:
            f.write(await vehicle_image.read())

    # Store just the relative path
    vehicle_image_path = f"public/fleets/{image_filename}" if image_filename else None

    fleet_data = {
        "fleet_name": fleet_name,
        "description": description,
        "status": status,
        "vehicle_id": vehicle_id,
        "registration_number": registration_number,
        "vin_number": vin_number,
        "vehicle_model_id": vehicle_model_id,
        "color": color,
        "year": year,
        "vehicle_image": vehicle_image_path,
        "insurance_number": insurance_number,
        "insurance_expiry": insurance_expiry.isoformat() if insurance_expiry else None,
        "vendor_id": vendor_id,
        "dealer_id": dealer_id,
        "fuel_type": fuel_type,
        "vehicle_type": vehicle_type,
        "capacity": capacity,
        "vendor_name": vendor_name,
        "tag_name": tag_name,
        "account_id": current_user.get("account_id", ""),
        "user_id": current_user.get("user_id", "")
    }

    result = create_fleet_service(fleet_data, db)
    
    # Ensure the response doesn't include binary data
    if result["fleet_data"].get("vehicle_image"):
        result["fleet_data"]["vehicle_image"] = f"http://localhost:8000/{result['fleet_data']['vehicle_image']}"

    return JSONResponse(
        content={"message": "Fleet created successfully", "fleet": result["fleet_data"]},
        status_code=201
    )

@router.get("/list/{account_id}/", response_model=FleetResponseList)
async def get_fleets(
    account_id: str,
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    status: Optional[str] = None,
    created_date_from: Optional[str] = None,
    created_date_to: Optional[str] = None,
    sort_by: Optional[str] = None,         # NEW
    sort_order: Optional[str] = "asc",     # NEW
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    if account_id != "all" and account_id != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return get_fleets_service(account_id, skip, limit, q, status, created_date_from, created_date_to, sort_by, sort_order, db)

@router.get("/{fleet_id}", response_model=Fleet)
async def read_fleet(
    fleet_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    print("146146146146146146146")
    fleet = read_fleet_service(fleet_id, db)
    
    if fleet.get("account_id") and fleet["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return fleet

@router.put("/{fleet_id}", response_model=Fleet)
async def update_fleet(
    fleet_id: str,
    fleet_data: FleetUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    existing_fleet = read_fleet_service(fleet_id, db)
    
    if existing_fleet.get("account_id") and existing_fleet["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return update_fleet_service(fleet_id, fleet_data.model_dump(exclude_unset=True), db)

@router.delete("/{fleet_id}", response_model=Fleet)
async def delete_fleet(
    fleet_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    existing_fleet = read_fleet_service(fleet_id, db)
    
    if existing_fleet.get("account_id") and existing_fleet["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return delete_fleet_service(fleet_id, db)

@router.post("/{fleet_id}/vehicles", response_model=Fleet)
async def add_vehicle_to_fleet(
    fleet_id: str,
    vehicle: VehicleBase,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    fleet = read_fleet_service(fleet_id, db)
    if fleet.get("account_id") != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    if not db.vehicles.find_one({"_id": ObjectId(vehicle.vehicle_model_id)}):
        raise HTTPException(status_code=404, detail="Vehicle model not found")
    
    if any(v["vehicle_id"] == vehicle.vehicle_id for v in fleet.get("vehicles", [])):
        raise HTTPException(status_code=400, detail="Vehicle ID already exists in this fleet")
    
    vehicle_data = vehicle.model_dump()
    result = db.fleets.update_one(
        {"_id": ObjectId(fleet_id)},
        {
            "$push": {"vehicles": vehicle_data},
            "$set": {"updated_date": datetime.utcnow()}
        }
    )
    
    if result.modified_count == 0:
        raise HTTPException(status_code=400, detail="Failed to add vehicle")
    
    db.vehicles.update_one(
        {"_id": ObjectId(vehicle.vehicle_model_id)},
        {"$addToSet": {"fleet_ids": fleet_id}}
    )
    
    return read_fleet_service(fleet_id, db)

@router.get("/{fleet_id}/vehicles", response_model=List[Dict[str, Any]])
async def get_fleet_vehicles(
    fleet_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    fleet = read_fleet_service(fleet_id, db)
    if fleet.get("account_id") != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return get_fleet_vehicles_service(fleet_id, db)

@router.get("/{fleet_id}/vehicles/{vehicle_id}", response_model=Dict[str, Any])
async def get_fleet_vehicle(
    fleet_id: str,
    vehicle_id: str,  # Changed from int to str
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    fleet = read_fleet_service(fleet_id, db)
    if fleet.get("account_id") != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    vehicle = next((v for v in fleet.get("vehicles", []) if v["vehicle_id"] == vehicle_id), None)
    if not vehicle:
        raise HTTPException(status_code=404, detail="Vehicle not found in fleet")
    
    model = db.vehicles.find_one({"_id": ObjectId(vehicle["vehicle_model_id"])})
    if model:
        vehicle["model_details"] = {
            "manufacturer_name": model.get("manufacturer_name", ""),
            "vehicle_type": model.get("vehicle_type", ""),
            "fuel_type": model.get("fuel_type", ""),
            "is_autonomous": model.get("is_autonomous", False),
            "can_fly": model.get("can_fly", False)
        }
    
    return vehicle

@router.put("/{fleet_id}/vehicles/{vehicle_id}", response_model=Fleet)
async def update_fleet_vehicle(
    fleet_id: str,
    vehicle_id: str,  # Changed from int to str
    vehicle_data: Dict[str, Any],
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    fleet = read_fleet_service(fleet_id, db)
    if fleet.get("account_id") != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    vehicle_index = next((i for i, v in enumerate(fleet["vehicles"]) if v["vehicle_id"] == vehicle_id), None)
    if vehicle_index is None:
        raise HTTPException(status_code=404, detail="Vehicle not found in fleet")
    
    updated_vehicles = fleet["vehicles"]
    updated_vehicles[vehicle_index] = {
        **updated_vehicles[vehicle_index],
        **vehicle_data,
        "vehicle_id": vehicle_id
    }
    
    result = db.fleets.update_one(
        {"_id": ObjectId(fleet_id)},
        {
            "$set": {
                "vehicles": updated_vehicles,
                "updated_date": datetime.utcnow()
            }
        }
    )
    
    if result.modified_count == 0:
        raise HTTPException(status_code=400, detail="Failed to update vehicle")
    
    return read_fleet_service(fleet_id, db)

@router.delete("/{fleet_id}/vehicles/{vehicle_id}", response_model=Fleet)
async def remove_vehicle_from_fleet(
    fleet_id: str,
    vehicle_id: str,  # Changed from int to str
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    fleet = read_fleet_service(fleet_id, db)
    if fleet.get("account_id") != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    vehicle = next((v for v in fleet.get("vehicles", []) if v["vehicle_id"] == vehicle_id), None)
    if not vehicle:
        raise HTTPException(status_code=404, detail="Vehicle not found in fleet")
    
    result = db.fleets.update_one(
        {"_id": ObjectId(fleet_id)},
        {
            "$pull": {"vehicles": {"vehicle_id": vehicle_id}},
            "$set": {"updated_date": datetime.utcnow()}
        }
    )
    
    if result.modified_count == 0:
        raise HTTPException(status_code=400, detail="Failed to remove vehicle")
    
    db.vehicles.update_one(
        {"_id": ObjectId(vehicle["vehicle_model_id"])},
        {"$pull": {"fleet_ids": fleet_id}}
    )
    
    return read_fleet_service(fleet_id, db)

@router.get("/dropdown/vehicles", response_model=List[Dict[str, str]])
async def get_vehicle_dropdown_list(
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails),
    q: str = Query(default="", description="Search query for fleet name"),
    all: str = Query(default="", description="Search all")
):
    account_id = current_user["account_id"]
    return get_fleet_dropdown_list(db, account_id, q,all)

