import openai
import subprocess
import re
import codecs

# Configurări pentru OpenAI
openai.api_base = "http://localhost:11434/v1"
openai.api_key = "ollama"
model_openai = "llama2"

# Funcție pentru a obține răspunsul de la modelul compatibil OpenAI
def get_response_from_openai(prompt, max_tokens=300):
    try:
        response = openai.ChatCompletion.create(
            model=model_openai,
            messages=[{"role": "user", "content": prompt}],
            temperature=0.7,
            max_tokens=max_tokens
        )
        return response['choices'][0]['message']['content'].strip()
    except Exception as e:
        return f"Error: {e}"

# Funcție pentru a extrage codul Python din răspunsul AI
def extract_code_from_response(response):
    code_match = re.search(r"```(?:python)?(.*?)```", response, re.DOTALL)
    if code_match:
        return code_match.group(1).strip()
    else:
        lines = response.split('\n')
        code_lines = []
        for line in lines:
            line = line.strip()
            if line and not line.startswith(('`', 'Of course', 'Here', 'This', 'Let', 'In this')):
                code_lines.append(line)
        return '\n'.join(code_lines).strip()

# Funcție pentru a rula codul generat și a captura ieșirea
def run_generated_code(code):
    try:
        with open("generated_script.py", "w", encoding="utf-8") as file:
            file.write(code)
        
        result = subprocess.run(["python", "generated_script.py"], capture_output=True, text=True)
        
        if result.returncode == 0:
            return f"Programul a rulat cu succes:\n{result.stdout}"
        else:
            return f"Eroare la rulare:\n{result.stderr}"
    except Exception as e:
        return f"Error: {e}"

# Funcție pentru a înregistra erorile într-un fișier jurnal
def log_error(topic, code, error):
    with open("error_log.txt", "a", encoding="utf-8") as log_file:
        log_file.write(f"Tema: {topic}\n")
        log_file.write(f"Cod generat:\n{code}\n")
        log_file.write(f"Eroare apărută:\n{error}\n")
        log_file.write("="*50 + "\n")

# Funcție principală pentru interacțiunea completă
def interactive_program_creation():
    while True:
        user_request = input("Descrieți programul pe care doriți să-l creați: ")

        prompt_for_ai1 = f"Te rog creează un program Python care să îndeplinească următoarele cerințe: {user_request}"
        generated_response = get_response_from_openai(prompt_for_ai1, max_tokens=300)
        generated_code = extract_code_from_response(generated_response)

        print(f"\nCod generat:\n{generated_code}\n")
        
        execution_result = run_generated_code(generated_code)
        print(f"\nRezultatul rulării:\n{execution_result}\n")

        while "Eroare la rulare" in execution_result or "Error" in execution_result:
            log_error(user_request, generated_code, execution_result)
            prompt_for_ai1_correction = f"Am încercat să rulez codul tău, dar a apărut următoarea eroare: {execution_result}. Poți să corectezi codul?"
            generated_response = get_response_from_openai(prompt_for_ai1_correction, max_tokens=300)
            generated_code = extract_code_from_response(generated_response)
            print(f"\nCod corectat:\n{generated_code}\n")
            
            execution_result = run_generated_code(generated_code)
            print(f"\nRezultatul rulării după corectare:\n{execution_result}\n")

        print("Codul a fost executat cu succes. Gata!")
        break

if __name__ == "__main__":
    interactive_program_creation()
