import json
import os
import random
import string
import re
import base64
import boto3
import chardet
from botocore.exceptions import BotoCoreError, ClientError
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from fastapi import HTTPException, status
from fastapi.responses import JSONResponse

# Load PDF UUIDs from the JSON file
def get_available_pdfs(json_path="pdf_uuids.json"):
    if os.path.exists(json_path):
        with open(json_path, "r") as file:
            pdf_uuids=json.load(file)
            return [details["pdf_name"] for details in pdf_uuids.values()]
    return []

# Function to save updated PDF UUIDs to the JSON file
def save_pdf_uuids(pdf_uuids, json_path="pdf_uuids.json"):
    with open(json_path, "w") as file:
        json.dump(pdf_uuids, file, indent=4)

def generate_random_text():
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))

def replace_special_characters(input_string):
    # Replace all non-alphanumeric characters (including spaces) with an underscore
    sanitized_string = re.sub(r'[^a-zA-Z0-9]', '_', input_string)
    return sanitized_string

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

def get_error_message(response):
    messages = [error["message"] for error in response.get("errors", [])]
    return messages

def validate_string_length(text,min_length,max_length):
    if len(text) < min_length or len(text) > max_length:
        return True
    else:
        return False

async def send_email(recipient: str, subject: str, body: str):

    conf = ConnectionConfig(
        MAIL_USERNAME=os.getenv('SES_ACCESS_KEY_ID'),
        MAIL_PASSWORD=os.getenv('SES_SECRET_ACCESS_KEY'),
        MAIL_FROM=os.getenv('SES_SENDER_EMAIL'),
        MAIL_PORT=465,
        MAIL_SERVER=os.getenv('SES_AWS_HOST'),
        MAIL_STARTTLS=False,
        MAIL_SSL_TLS=True,
        USE_CREDENTIALS=True
    )
    
    message = MessageSchema(
        subject=subject,
        recipients=[recipient],  # List of recipients
        body=body,
        subtype="html"
    )
    fm = FastMail(conf)
    try:
        await fm.send_message(message)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Send Email Function
def send_email_ses(recipient: str, subject: str, body: str):
    AWS_REGION = os.getenv('SES_AWS_REGION')  # Replace with your SES region
    AWS_ACCESS_KEY_ID = os.getenv('SES_ACCESS_KEY_ID')
    AWS_SECRET_ACCESS_KEY = os.getenv('SES_SECRET_ACCESS_KEY')
    SES_SENDER_EMAIL = os.getenv('SES_SENDER_EMAIL')
    try:
        # Initialize SES Client
        ses_client = boto3.client(
            "ses",
            region_name=AWS_REGION,
            aws_access_key_id=AWS_ACCESS_KEY_ID,
            aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
        )
        response = ses_client.send_email(
            Source=SES_SENDER_EMAIL,
            Destination={
                "ToAddresses": [recipient],
            },
            Message={
                "Subject": {
                    "Data": subject,
                },
                "Body": {
                    "Text": {
                        "Data": body,
                    },
                },
            },
        )
        return response
    except (BotoCoreError, ClientError) as error:
        raise HTTPException(status_code=500, detail=str(error))


# Parse SCORM content to extract readable text
def parse_scorm_content(directory: str) -> list:
    content_data = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(".html") or file.endswith(".txt"):
                with open(os.path.join(root, file), "rb") as f:
                    raw_data = f.read()
                    # Detect encoding
                    detected_encoding = chardet.detect(raw_data)['encoding']
                    if not detected_encoding:
                        detected_encoding = "utf-8"  # Fallback encoding
                    try:
                        text = raw_data.decode(detected_encoding)
                    except UnicodeDecodeError:
                        text = raw_data.decode(detected_encoding, errors="replace")  # Replace problematic characters

                    content_data.append({"id": file, "text": text})
    return content_data

def normalize_spaces(input_string):
    return re.sub(r'\s+', ' ', input_string).strip()

def errorResponse(message,status_code = 400):
    if not status_code:
        status_code = status.HTTP_400_BAD_REQUEST

    return JSONResponse(
        status_code=status_code,
        content={
            "status": status_code,
            "message": message,
        },
    )
def successReponse(message, data):
	return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={
            "status": status.HTTP_200_OK,
            "message": message,
            "data": data
        },
    )