import os
import requests
import time
from colorama import init, Fore, Style
from datetime import datetime

init()

def get_ollama_host():
    return input("Introduce adresa OLLAMA_HOST: ")

def get_ai_response(host, message, model="llama3.3"):
    try:
        response = requests.post(
            f"{host}/api/chat",
            json={
                "model": model,
                "messages": [{"role": "user", "content": message}],
                "stream": False
            }
        )
        response.raise_for_status()
        return response.json()['message']['content']
    except Exception as e:
        return f"Error: {str(e)}"

def print_and_save(file, text, color=Fore.WHITE, delay=0.02):
    # Print cu efect de typing
    for char in text:
        print(color + char + Style.RESET_ALL, end='', flush=True)
        time.sleep(delay)
    print()
    
    # Salvare în fișier (fără culori)
    file.write(text + '\n')

def ai_debate():
    host = get_ollama_host()
    topic = input("Introduce tema dezbaterii: ")
    cycles = int(input("Număr de cicluri de discuție: "))
    
    # Creare fișier pentru salvare
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"dezbatere_{timestamp}.txt"
    
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(f"Dezbatere pe tema: {topic}\n")
        f.write(f"Data: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write("-" * 50 + "\n\n")
        
        print("\nÎncepe dezbaterea...")
        context_pro = f"Ești InterlocutorAI001. Susții argumentele PRO pentru tema: {topic}"
        context_contra = f"Ești InterlocutorAI002. Susții argumentele CONTRA pentru tema: {topic}"
        
        debate_history = []
        
        for i in range(cycles):
            cycle_header = f"--- Ciclu {i+1}/{cycles} ---"
            print(f"\n{Fore.YELLOW}{cycle_header}{Style.RESET_ALL}")
            f.write(f"\n{cycle_header}\n")
            
            # Pro argument
            pro_response = get_ai_response(host, context_pro)
            print(f"\n{Fore.CYAN}InterlocutorAI001 (PRO):{Style.RESET_ALL}")
            f.write("\nInterlocutorAI001 (PRO):\n")
            print_and_save(f, pro_response, Fore.BLUE)
            debate_history.append(pro_response)
            
            # Contra argument
            contra_message = f"{context_contra}. Răspunde la argumentul: {pro_response}"
            contra_response = get_ai_response(host, contra_message)
            print(f"\n{Fore.LIGHTRED_EX}InterlocutorAI002 (CONTRA):{Style.RESET_ALL}")
            f.write("\nInterlocutorAI002 (CONTRA):\n")
            print_and_save(f, contra_response, Fore.RED)
            debate_history.append(contra_response)
        
        # Concluzie finală
        conclusion_header = "--- Concluzie Finală ---"
        print(f"\n{Fore.YELLOW}{conclusion_header}{Style.RESET_ALL}")
        f.write(f"\n{conclusion_header}\n")
        
        conclusion_prompt = f"""Ca observator obiectiv, analizează următoarea dezbatere pe tema '{topic}' 
        și trage o concluzie bazată pe ultimele argumente prezentate:
        Ultimul argument PRO: {debate_history[-2]}
        Ultimul argument CONTRA: {debate_history[-1]}"""
        
        conclusion = get_ai_response(host, conclusion_prompt)
        print(f"\n{Fore.GREEN}Concluzie:{Style.RESET_ALL}")
        f.write("\nConcluzie:\n")
        print_and_save(f, conclusion, Fore.GREEN)
        
    print(f"\nDezbaterea a fost salvată în fișierul: {filename}")

if __name__ == "__main__":
    ai_debate()
