import matplotlib.pyplot as plt
from LLM_openai import client, expense_classifier
import datetime
import base64
from io import BytesIO
import re
import json
import matplotlib.dates as mdates

def create_plot(x, y):
    fig, ax = plt.subplots()
    ax.plot(x, y, marker='o')
    for i in range(len(x)):
        ax.text(x[i], y[i], f'{y[i]:.2f}', fontsize=10, ha='left', va='bottom')
    ax.set_xlabel('Dinero')
    ax.set_ylabel('Gasto')
    ax.set_title('Gasto diario')
    ax.set_xticks(x[::5])  # Show every 5th day
    ax.set_xticklabels(x[::5], rotation=45, ha='right') 
    plt.xticks(rotation=30)
    return fig


def create_barplot(x, y, xlabel,ylabel, title):
    fig, ax = plt.subplots()
    ax.bar(x, y)
    for i in range(len(x)):
        ax.text(x[i], y[i], f'{y[i]:.2f}', fontsize=10, ha='left', va='bottom')
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(title)
    plt.xticks(rotation=30)
    return fig


####
##OCR functions



def pil_to_base64(pil_img):
    img_buffer = BytesIO()
    pil_img.save(img_buffer, format='JPEG')
    byte_data = img_buffer.getvalue()
    base64_str = base64.b64encode(byte_data).decode("utf-8")
    return base64_str

def js_to_prefere_the_back_camera_of_mobilephones():
    custom_html = """
    <script>
    const originalGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
    
    navigator.mediaDevices.getUserMedia = (constraints) => {
      if (!constraints.video.facingMode) {
        constraints.video.facingMode = {ideal: "environment"};
      }
      return originalGetUserMedia(constraints);
    };
    </script>
    """
    return custom_html

def result_cleaner(text):
    pattern = r'\{[^}]*\}'
    match = re.search(pattern, text)
    match_string=match[0]
    json_dict=json.loads(match_string)


    return json_dict