from datetime import date, datetime
from openai import OpenAI
from pathlib import Path
import shutil
import yaml

key_path = Path.home() / "personal openai key.txt"
with key_path.open() as f:
    key = f.read().strip()

client = OpenAI(api_key=key)

prompt_template = """What is the cheapest price I can get this car {car}? Prefer used prices since they are cheaper.
Just output the price and nothing else. Do not write any information or comments beyond the price. Do not format it. It should just be a plain number, no $ sign or , splitting digits or anything to format the number. If tire size is specified, it is referring to the trim with that tire size."""

def load_data():
    with open("cars.yaml", "r") as file:
        data = yaml.safe_load(file)
    return data

def save_data(data):
    now = datetime.now()
    today = date.today()
    today = today.strftime("%B %d, %Y")
    data['last price update'] = today
    timestamp = now.strftime("%Y-%m-%d %H-%M-%S")
    shutil.copy("cars.yaml", f"cars old {timestamp}.yaml")
    with open('cars.yaml', 'w') as f:
        yaml.dump(data, f, default_flow_style=False)
    print("saved data")

def get_price(car):
    prompt = prompt_template.replace("{car}", car)
    price = None
    while price is None:
        print(f"Finding price for {car}")
        try:
            completion = client.chat.completions.create(
                model="gpt-4o-mini-search-preview",
                web_search_options={},
                messages=[
                    {
                        "role": "user",
                        "content": prompt,
                    }
                ],
            )
            content = completion.choices[0].message.content
            content = content.replace("$", "").replace(",", "").strip()
            content = float(content)
            price = content
        except ValueError as e:
            print(e)
            print("Failed. Trying again.")
    print(f"Got price of {car} as ${price:,.2f}")
    return price

def update_prices(data):
    for car in data['EVs']:
        price = get_price(car)
        data['EVs'][car]['used price'] = price
    for car in data['gas']:
        price = get_price(car)
        data['gas'][car]['used price'] = price

def main():
    data = load_data()
    update_prices(data)
    save_data(data)

if __name__ == "__main__":
    main()
