import logging
import csv
import io
import base64
from fastapi import HTTPException
from core import Models
from services.agent_helpers.reasoning_prompts import ASK_PROMPT, EVALUATE_PROMPT

logger = logging.getLogger(__name__)

class ReasoningService:
    def __init__(self, pgvector, db_service, openai_service, tts_service):
        self.pgvector = pgvector
        self.db_service = db_service
        self.openai = openai_service 
        self.tts = tts_service
        # Initialize tables automatically
        self.pgvector.setup_reasoning_tables()

    def bulk_upload_questions(self, csv_content: bytes, grade: int):
        try:
            decoded = csv_content.decode('utf-8-sig') 
            reader = csv.DictReader(io.StringIO(decoded))
            
            with self.pgvector.pool_handler.get_connection() as conn:
                with conn.cursor() as cur:
                    count = 0
                    for row in reader:
                        row = {k.strip(): v for k, v in row.items() if k}
                        q_text = row.get('السؤال') or row.get('question_text')
                        a_text = row.get('الاجابة') or row.get('model_answer')
                        
                        if q_text and a_text:
                            cur.execute(
                                "INSERT INTO reasoning_questions (grade, question_text, model_answer) VALUES (%s, %s, %s)",
                                (grade, q_text.strip(), a_text.strip())
                            )
                            count += 1
                    conn.commit()
            print(f"Successfully uploaded {count} questions for grade {grade}")
            return True
        except Exception as e:
            logger.error(f"Failed to upload reasoning CSV: {e}")
            return False

    def get_atom_challenge(self, student_id: str):
        # 1. Retrieve student info
        student_info = self.db_service.get_student_info(student_id)
        if not student_info:
            logger.error(f"Student {student_id} not found")
            raise HTTPException(status_code=404, detail="Student not found")
        
        grade = student_info.grade
        student_name = student_info.student_name

        # 2. Get random question
        question_data = self.pgvector.get_random_reasoning_question(grade)
        if not question_data:
            logger.error(f"No questions found for grade {grade}")
            raise HTTPException(status_code=404, detail="No questions found for this grade.")

        # 3. Save session reference
        self.pgvector.update_reasoning_session(student_id, question_data['id'])

        # 4. Atomize the question
        prompt = ASK_PROMPT.format(student_name=student_name, question_text=question_data['question_text'])
        ai_response = self.openai.client.chat.completions.create(
            model=Models.chat, 
            messages=[{"role": "user", "content": prompt}]
        )
        atom_text = ai_response.choices[0].message.content
        
        self.db_service.add_message(student_id, 'assistant', atom_text)
        
        audio_bytes = self.tts.generate_speech(atom_text)
        return atom_text, audio_bytes

    def evaluate_student_answer(self, student_id: str, audio_content: bytes, filename: str):
        student_info = self.db_service.get_student_info(student_id)
        active_q = self.pgvector.get_active_reasoning_question(student_id)
        if not active_q: 
            raise HTTPException(status_code=400, detail="No active reasoning session.")

        student_said = self.openai.transcribe_audio(audio_content, filename)

        self.db_service.add_message(student_id, 'user', student_said)

        recent_history = self.db_service.get_chat_history(student_id, limit=5)
        history_context = "\n".join([f"{m['role']}: {m['content']}" for m in recent_history])

        prompt = EVALUATE_PROMPT.format(
            student_name=student_info.student_name,
            question_text=active_q['question_text'],
            model_answer=active_q['model_answer'],
            student_answer=student_said
        )
        
        messages = [
            {"role": "system", "content": "Recent context:\n" + history_context},
            {"role": "user", "content": prompt}
        ]

        ai_eval = self.openai.client.chat.completions.create(
            model=Models.chat, 
            messages=messages,
            temperature=0.3
        )
        feedback_text = ai_eval.choices[0].message.content
        
        self.db_service.add_message(student_id, 'assistant', feedback_text)
        audio_bytes = self.tts.generate_speech(feedback_text)
        return feedback_text, audio_bytes, student_said