import json
import re
from transformers import pipeline
import MySQLdb
import os
import logging

# Load the QA pipeline using the distilbert-base-uncased-distilled-squad model
qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")

def get_next_part(app_id, phase):
    conn = MySQLdb.connect(
        host="localhost",
        user="openai_user",
        passwd="IOyg76H2l%252BewRX2xhsDJAo7qnfVDHtx9RB%253D%",  # or os.getenv("DB_PASSWORD")
        db="openai_prompts",
        charset="utf8mb4"
    )
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("""
        SELECT instruction_text, question_text, ai_prompt_id, feedbackRequest_text, prompt_template_name, section_label
        FROM phase_content
        WHERE app_id = %s AND phase_number = %s
    """, (app_id, phase))
    result = cursor.fetchone()
    conn.close()
    logging.info(f"🔎 QA_SYSTEM: Phase data fetched: {result}")
    return result


def get_prompt_messages_by_template_name(name):
    conn = MySQLdb.connect(
        host="localhost",
        user="openai_user",
        passwd="IOyg76H2l%252BewRX2xhsDJAo7qnfVDHtx9RB%253D%",
        db="openai_prompts",
        charset="utf8mb4"
    )
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)

    cursor.execute("""
        SELECT id FROM prompt_templates
        WHERE name = %s
    """, (name,))
    row = cursor.fetchone()
    if not row:
        conn.close()
        return []

    prompt_id = row["id"]

    cursor.execute("""
        SELECT role, content FROM prompt_messages
        WHERE prompt_id = %s
        ORDER BY sequence
    """, (prompt_id,))
    messages = cursor.fetchall()
    conn.close()
#    logging.debug(f"🧪 Messages type: {type(messages)} | First item: {type(messages[0]) if messages else 'None'}")
    return [dict(msg) for msg in messages]  # ✅ Ensures it's always a list of dicts
#    return messages



def remove_headers(text):
    """
    Removes headers that are all uppercase and surrounded by dashes.
    :param text: The text to process.
    :return: Text with headers removed.
    """
    # Use regex to remove all uppercase headers surrounded by dashes
    return re.sub(r'-[A-Z\s]+-', '', text).strip()


def get_answer(question, context):
    """
    Get an answer from the model based on a question and context.
    :param question: The question asked
    :param context: The context for the question
    :return: The model's answer
    """
    result = qa_pipeline(question=question, context=context)
    return result["answer"]

def get_recommendation(feedback):
    """
    Generate a recommendation based on the feedback given.
    :param feedback: User feedback text
    :return: Recommendation based on feedback
    """
    feedback = feedback.lower()
    if "good" in feedback or "okay" in feedback:
        return "Thank you. It's about you how you will proceed, but I recommend going ahead."
    elif "bad" in feedback or "not ready" in feedback:
        return "Take your time. If you're not ready, feel free to repeat the phase."
    else:
        return "I understand. You can decide whether to continue or repeat the phase."
    

def extract_chapter(text, start_marker, end_marker):
    """
    Extract text between two markers, excluding the start and end markers.
    :param text: The full text.
    :param start_marker: Start of the section.
    :param end_marker: End of the section.
    :return: Extracted text.
    """
    start_index = text.find(start_marker)
    end_index = text.find(end_marker, start_index)

    # Debug: Check if the markers are found correctly
    print(f"Start marker found at: {start_index}, End marker found at: {end_index}")


    if start_index == -1 or end_index == -1:
        raise ValueError(f"Could not find markers '{start_marker}' and '{end_marker}' in text.")

    # Extract the text between markers but skip the actual start_marker
    extracted_text = text[start_index + len(start_marker):end_index].strip()

    # Remove headers (all caps surrounded by dashes)
    # extracted_text = remove_headers(extracted_text)

    print(f"Extracted text (after header removal): {extracted_text[:100]}...")  # Debug: Log first 100 chars

    return extracted_text

def sanitize_text(text):
    """
    Sanitizes the text by removing unwanted characters.
    :param text: The text to sanitize.
    :return: Sanitized text.
    """
    return text.replace('\r', '').strip()


def get_default_questions():
    """
    Returns default questions if no specific questions are found for a phase.
    :return: List of default questions.
    """
    return [
        {"text": "(A) Proceed to the next phase.", "choice": "A"},
        {"text": "(B) Repeat the current phase.", "choice": "B"}
    ]

def get_phase_context(phase):
    """
    Returns the context for a given phase, used as input for the AI model.
    :param phase: The current phase
    :return: Context string for the phase
    """
    context_mapping = {
        1: "Context for phase 1",
        2: "Context for phase 2",
        3: "Context for phase 3",
        4: "Context for phase 4",
        5: "Context for phase 5",
        6: "Context for phase 6",
        7: "Context for phase 7",
        8: "Context for phase 8",
        9: "Context for phase 9",
        10: "Context for phase 10",
        11: "Context for phase 11",
        12: "Context for phase 12",
        13: "Context for phase 13",
        14: "Context for phase 14"
    }
    return context_mapping.get(phase, "Unknown phase context")

def detect_app_id_from_port(host):
    try:
        port = host.split(":")[-1]
        return {
            "5000": 1,
            "5001": 2,
            "5006": 3
        }.get(port, 1)  # Default to app_id = 1
    except Exception:
        return 1
