"""
Services module
"""

import requests
import json
from .utils import get_jwt_token
from pyvin import VIN
from django.conf import settings
from openai import OpenAI
from .models import Car,CarMake,CarModel


def get_make(item):    
    data = CarMake.objects.filter(name__iexact=item).first()    
    return data
def get_model(item,make):    
    data = make.carmodel_set.filter(name__iexact=item).first()
    if not data:
        r = item.split(" ")
        for i in r:                        
            if data:=make.carmodel_set.filter(name__iexact=i).first():
                break                                      
    return data

def normalize_name(name):
    return name.replace(" ", "").replace("-", "").lower()


def decodevin(vin):
    
    if result:=decode_vin(vin):
        return result
    elif result:=elm(vin):
        return result
    else:
        return None



def decode_vin(vin):
    v = VIN(vin)
    data = {}
    if v:        
        data = {
            "maker": v.Make,
            "model": v.Model,
            "modelYear": v.ModelYear,
        }

    return data if all([x for x in data.values()]) else None


# vehicle-info
# c2729afb
# 6d397471920412d672af1b8a02ca52ea


# option-info
# 367974ed
# 046b0412c1b4d3f8c39ec6375d6f3030
def elm(vin):
    headers = {
        "Content-Type": "application/json",
        "app-id": "c2729afb",
        "app-key": "6d397471920412d672af1b8a02ca52ea",
        "client-id": "94142c27-2536-47e9-8e28-9ca7728b9442",
    }
    url = (
        "https://vehicle-maintenance.api.elm.sa/api/v1/vehicles/vehicle-info?vin=" + vin
    )

    payload = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    response = json.loads(response.text)
    data = {}
    if response.get("data"):
        data = {
            "maker": response["data"]["maker"],
            "model": response["data"]["model"],
            "modelYear": response["data"]["modelYear"],
        }

    return data if all([x for x in data.values()]) else None    


def translate(content, *args, **kwargs):
    client = OpenAI(api_key=settings.OPENAI_API_KEY)
    completion = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {
                "role": "system",
                "content": "You are a translation assistant that translates English to Arabic.",
            },
            {"role": "user", "content": content},
        ],
        temperature=0.3,
    )
    translation = completion.choices[0].message.content.strip()
    return translation


def calculate_stock_value():
    cars = Car.objects.all()
    total_value = sum(car.selling_price for car in cars)
    return total_value
