from fastapi import HTTPException
from app.v1.models.platform.iotdevices import IotDeviceCreate, IotDeviceUpdate
from app.v1.libraries.object import str_to_objectid
from datetime import datetime
from pymongo import ASCENDING, DESCENDING
from typing import Optional

COLLECTION_NAME = "iot_devices"


async def create_iot_device_service(device: IotDeviceCreate, db):
    data = device.dict()
    data["created_date"] = datetime.utcnow()
    result = db[COLLECTION_NAME].insert_one(data)
    data["id"] = str(result.inserted_id)
    return data


async def get_iot_device_service(account_id: str, db):
    device = db[COLLECTION_NAME].find_one({"_id": str_to_objectid(account_id)})
    if not device:
        raise HTTPException(status_code=404, detail="IoT Device not found")
    device["id"] = str(device["_id"])
    return device


async def update_iot_device_service(account_id: str, update: IotDeviceUpdate, db):
    update_data = {k: v for k, v in update.dict(exclude_unset=True).items()}
    update_data["last_updated"] = datetime.utcnow()
    await db[COLLECTION_NAME].update_one({"_id": str_to_objectid(account_id)}, {"$set": update_data})
    return await get_iot_device_service(account_id, db)


async def delete_iot_device_service(account_id: str, db):
    device = await get_iot_device_service(account_id, db)
    await db[COLLECTION_NAME].delete_one({"_id": str_to_objectid(account_id)})
    return device

async def list_iot_devices_service(skip, limit, q: Optional[str], device_type, status, date_from, date_to, db):
    filter_query = {}

    if q:
        regex_query = {"$regex": q, "$options": "i"}
        filter_query["$or"] = [
            {"model_name": regex_query},
            {"installation_details": regex_query}
        ]

    if device_type:
        filter_query["device_type"] = device_type

    if status:
        filter_query["status"] = status

    if date_from or date_to:
        date_filter = {}
        if date_from:
            date_filter["$gte"] = datetime.strptime(date_from, "%Y-%m-%d")
        if date_to:
            date_filter["$lte"] = datetime.strptime(date_to, "%Y-%m-%d")
        filter_query["created_date"] = date_filter

    cursor = db[COLLECTION_NAME].find(filter_query).skip(skip).limit(limit)

    devices = []
    for d in cursor:
        d["id"] = str(d["_id"])
        devices.append(d)

    total = db[COLLECTION_NAME].count_documents(filter_query)
    return {"total_count": total, "users": devices}
