# main.py

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import openai
import uvicorn

app = FastAPI()

# Define models for data validation
class Summarize(BaseModel):
    diagnose: str
    cause: str
    solution: str

class StoredResponse(BaseModel):
    selected_response: str
    diagnose: str
    cause: str
    solution: str

# Initialize OpenAI API key
openai.api_key = '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'

# Database to store stored responses (simulated in-memory database)
stored_responses = []

# Function to check if a stored response exists for a given input
def find_stored_response(diagnose: str, cause: str, solution: str) -> Optional[StoredResponse]:
    for response in stored_responses:
        if (
            response.diagnose == diagnose
            and response.cause == cause
            and response.solution == solution
        ):
            return response
    return None

# Summarize endpoint
@app.post("/summarize/", response_model=dict)
async def summarize(item: Summarize):
    # Check if a stored response exists for the input
    existing_response = find_stored_response(item.diagnose, item.cause, item.solution)
    if existing_response:
        return [existing_response.selected_response]

    # Use OpenAI's GPT-3 to generate a summary
    user_input = (
        f"Diagnose: {item.diagnose}\n"
        f"Cause: {item.cause}\n"
        f"Solution: {item.solution}\n"
    )
    prompt = "Translate and summarize Norwegian inputs about 'Diagnose', 'Cause', and 'Løsning og resultat' into English outputs of 'Diagnosis' and 'Solution', each strictly limited to 72 characters. When using domain-specific terminology, refer to the dictionary to understand or include relevant acronyms: acronym_dictionary = { OBC: On-Board Charger, E_VCU: Electronic Vehicle Control Unit, TSB: Technical Service Bulletin, (Examples) U2FFF / B1004 96 / U1F2F 87 / P1B74 / P000A 00: This is an error code that was registered in the fault log of the vehicle., TSB D1BW011FQ0: Code, HV battery: High Volt battery, ECU: Engine Control Unit, VOR: Vehicle Off Road, DID: Deal Issue Detection, DID-I: Dealer Issue Detection Incident, DID-A: Dealer Issue Detection Assistance, DID-S: Dealer Issue Detection Safety, EV-ECU: Electric Vehicle ECU, BMU or TBMU: Traction Battery ECU, HPCU: Hybrid Control Unit, MCU: Inverter, iSolve: Repair Solution, DPF: Diesel Particle Filter, EGR: Exhaust Gas Recirculation, DA: Documents (Sharing Platform), Reman: Remanufactured Parts, DTC: Diagnostic Trouble Code, DARS: Documents }.Always mention TSB, mentioned codes and Kilometers or units with details.GIVE 3 DIFFERENT RESPONSES IN NEW LINES WITH SPECIAL NUMBERINGS LIKE #1 #2 #3. Example: #1. Diagnosis: Text. \nSolution: Text.\n#2. Diagnosis: Text. \nSolution: Text.\n#3. Diagnosis: Text. \nSolution: Text."
    
    response = openai.Completion.create(
    engine="text-davinci-002",
    prompt=prompt + "\n" + user_input,
    max_tokens=3000
)
    
    gpt_response = response.choices[0].text.strip()
    response_parts = gpt_response.split('\n#')
    
    if len(response_parts) >= 3:
        response1 = response_parts[0]
        response2 = response_parts[1]
        response3 = response_parts[2]
    else:
        response1 = response_parts[0] if len(response_parts) >= 1 else ""
        response2 = response_parts[1] if len(response_parts) >= 2 else ""
        response3 = ""

    if response1.startswith("#"):
        response1 = response1[1:]
    else:
        response1 = response1

    response1 = response1.strip()
    response2 = response2.strip()
    response3 = response3.strip()

    response_dict = {
        "Response 1": response1,
        "Response 2": response2,
        "Response 3": response3
    }

    return response_dict

# Store Response endpoint
@app.post("/store-response/", response_model=StoredResponse)
async def store_selected_response(item: StoredResponse):
    # Check if a stored response with the same input already exists
    existing_response = find_stored_response(item.diagnose, item.cause, item.solution)
    if existing_response:
        # Update the existing response
        existing_response.selected_response = item.selected_response
        return existing_response

    # If no matching stored response, create a new one
    stored_responses.append(item)
    return item

# Check Response endpoint
@app.post("/check-response/", response_model=StoredResponse)
async def check_stored_response(item: Summarize):
    # Check if a stored response exists for the input
    stored_response = find_stored_response(item.diagnose, item.cause, item.solution)
    if stored_response:
        return stored_response
    
    # If no stored response found, raise an HTTPException with 404 status code
    raise HTTPException(status_code=404, detail="No stored response found")

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)