from flask import Blueprint, request, jsonify, render_template
import requests
from app import mysql
from app.config import Config
import uuid
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import re
from flask_cors import CORS
from google.oauth2 import service_account
from googleapiclient.discovery import build
import json
from dateutil import parser
from dateutil.relativedelta import relativedelta
import logging
import os
from datetime import datetime, timedelta
import pytz
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import MySQLdb.cursors
from app.routes.auth import require_basic_auth

api_bp = Blueprint('api', __name__)

# Enable CORS with credentials support
CORS(api_bp, resources={
    r"/api/*": {
        "origins": "*",
        "methods": ["GET", "POST", "OPTIONS"],
        "allow_headers": ["Content-Type", "X-Response-Type", "Authorization"],
        "expose_headers": ["Content-Type", "X-Response-Type"],
        "supports_credentials": True,
        "allow_credentials": True
    }
})

# Add CORS headers to all responses
@api_bp.after_request
def add_cors_headers(response):
    origin = request.headers.get('Origin')
    if origin:
        response.headers['Access-Control-Allow-Origin'] = origin
        
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Response-Type, Authorization'
    return response

@api_bp.route('/api/<company_id>/chat', methods=['OPTIONS'])
def handle_options(company_id):
    return '', 204

SERVICE_ACCOUNT_FILE = 'config/gpt-ronnie-9ad6512012b3.json'

# Verify the file exists
if not os.path.exists(SERVICE_ACCOUNT_FILE):
    raise FileNotFoundError(f"Service account file not found at {SERVICE_ACCOUNT_FILE}")

# Add these constants at the top of the file
SCOPES = ['https://www.googleapis.com/auth/calendar']

# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

def get_website_content(url):
    try:
        if url.startswith('@'):
            url = url[1:]
        
        
        if not url.startswith(('http://', 'https://')):
            url = 'https://' + url
            
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        response = requests.get(url, headers=headers, timeout=15)
        soup = BeautifulSoup(response.text, 'html.parser')
        
        links = []
        seen_urls = set()
        base_domain = urlparse(url).netloc
        
        for a in soup.find_all('a', href=True):
            href = a['href']
            full_url = urljoin(url, href)
            parsed_url = urlparse(full_url)
            
            if (parsed_url.netloc == base_domain and 
                full_url not in seen_urls and 
                not href.startswith(('#', 'javascript:', 'mailto:', 'tel:'))):
                
                seen_urls.add(full_url)
                text = a.get_text().strip()
                
                # Clean up the text
                text = re.sub(r'\s+', ' ', text).strip()
                
                if text:
                    link_data = {
                        'url': full_url,
                        'text': text[:255]
                    }
                    links.append(link_data)
                    print(f"Found link: {link_data['text']} -> {link_data['url']}")
        
        print(f"Total links found: {len(links)}")
        return links
        
    except Exception as e:
        print(f"Error crawling website: {str(e)}")
        return []

def find_relevant_urls(website_url, query, company_id):
    try:
        cursor = mysql.connection.cursor()
        print(f"Searching URLs for company {company_id} with query: {query}")  # Debug log
        
        # First check if we have cached URLs
        cursor.execute("""
            SELECT url, page_title 
            FROM website_pages 
            WHERE company_id = %s
        """, (company_id,))
        
        cached_pages = cursor.fetchall()
        print(f"Found {len(cached_pages) if cached_pages else 0} cached pages")  
        
        if not cached_pages:
            print(f"No cached pages found, crawling website: {website_url}")  
            links = get_website_content(website_url)
            print(f"Crawled {len(links)} links from website")  
            
            # Store the links in database
            for link in links:
                try:
                    cursor.execute("""
                        INSERT INTO website_pages (id, company_id, url, page_title, page_content)
                        VALUES (%s, %s, %s, %s, %s)
                    """, (str(uuid.uuid4()), company_id, link['url'], link['text'], ''))
                except Exception as e:
                    print(f"Error storing URL {link['url']}: {str(e)}")
            
            mysql.connection.commit()
            
            # Refresh cached pages after storing
            cursor.execute("""
                SELECT url, page_title 
                FROM website_pages 
                WHERE company_id = %s
            """, (company_id,))
            cached_pages = cursor.fetchall()
        
        # Search for relevant URLs based on query
        search_terms = query.lower().split()
        
        # Special handling for contact page queries
        if 'contact' in query.lower():
            cursor.execute("""
                SELECT url, page_title 
                FROM website_pages 
                WHERE company_id = %s 
                AND (
                    LOWER(page_title) LIKE '%contact%' 
                    OR LOWER(url) LIKE '%contact%'
                    OR LOWER(page_title) LIKE '%reach%'
                    OR LOWER(url) LIKE '%reach-us%'
                )
            """, (company_id,))
        else:
            cursor.execute("""
                SELECT url, page_title 
                FROM website_pages 
                WHERE company_id = %s 
                AND (LOWER(page_title) LIKE %s OR LOWER(url) LIKE %s)
            """, (company_id, f"%{search_terms[0]}%", f"%{search_terms[0]}%"))
        
        relevant_urls = cursor.fetchall()
        print(f"Found {len(relevant_urls)} relevant URLs")  # Debug log
        return relevant_urls
        
    except Exception as e:
        print(f"Error in find_relevant_urls: {str(e)}")
        return []

def create_meeting_prompt(company_name):
    return f"""When handling meeting scheduling requests, strictly follow this process:

    1. When user mentions scheduling/booking a meeting:
       Response: "I'll help you schedule a meeting. First, please provide your email address."

    2. After receiving email:
       Response: "Thank you. What date would you like to schedule the meeting for? You can use YYYY-MM-DD format or say something like 'tomorrow' or 'next Monday'."

    3. After receiving date:
       Response: "Got it. What time would you prefer? Please use 24-hour format (HH:MM), for example: 14:30"

    4. After receiving time:
       Show confirmation message:
       "Please review these meeting details:
       - Email: [collected_email]
       - Date: [formatted_date]
       - Time: [formatted_time]
       
       Type 'confirm' to schedule the meeting or 'cancel' to start over."


    Important:
    - Always validate email format
    - Convert natural language dates to YYYY-MM-DD format
    - Ensure time is in HH:MM format
    - Only proceed to scheduling after explicit confirmation
    - Store meeting details in database after confirmation
    """
def parse_natural_date(date_str):
    """Convert natural language date or standard date format to YYYY-MM-DD format and readable format"""
    try:
        # First check if it's already in YYYY-MM-DD format
        if re.match(r'^\d{4}-\d{2}-\d{2}$', date_str):
            parsed_date = datetime.strptime(date_str, '%Y-%m-%d')
            return {
                'iso_date': date_str,
                'readable_date': parsed_date.strftime('%A, %B %d, %Y')
            }
        
        # Get current date in UTC
        now = datetime.now(pytz.UTC)
        date_str = date_str.lower().strip()

        weekdays = {
            'monday': 0,
            'tuesday': 1,
            'wednesday': 2,
            'thursday': 3,
            'friday': 4,
            'saturday': 5,
            'sunday': 6
        }

        if date_str == 'today':
            parsed_date = now
        elif date_str == 'tomorrow':
            parsed_date = now + timedelta(days=1)
        elif date_str.startswith('next ') and date_str[5:] in weekdays:
            target_day = weekdays[date_str[5:]]
            current_day = now.weekday()
            days_ahead = (target_day - current_day + 7) % 7
            days_ahead = days_ahead if days_ahead != 0 else 7
            parsed_date = now + timedelta(days=days_ahead)
        else:
            # Try to parse other formats using dateutil
            parsed_date = parser.parse(date_str, fuzzy=True)
            # If the parsed date is in the past, optionally push it to the next week
            if parsed_date < now and 'next' not in date_str:
                parsed_date += relativedelta(weeks=1)

        # Ensure we have a datetime object
        if isinstance(parsed_date, timedelta):
            parsed_date = now + parsed_date

        # Convert to UTC if not already
        if parsed_date.tzinfo is None:
            parsed_date = pytz.UTC.localize(parsed_date)

        # Format the date
        return {
            'iso_date': parsed_date.strftime('%Y-%m-%d'),
            'readable_date': parsed_date.strftime('%A, %B %d, %Y')
        }

    except Exception as e:
        print(f"Error parsing date '{date_str}': {str(e)}")
        return None

@api_bp.route('/api/<company_id>/chat', methods=['POST'])
def company_chat(company_id):
    try:
        data = request.json
        user_message = data.get('message')
        session_id = data.get('session_id', str(uuid.uuid4()))
        is_voice = data.get('is_voice', False)
        cursor = mysql.connection.cursor()
        
        # Get company information including both instructions and documents
        cursor.execute("""
            SELECT 
                c.name, 
                c.instructions, 
                c.website,
                GROUP_CONCAT(DISTINCT d.file_content SEPARATOR '\n---\n') as doc_content,
                c.welcome_message
            FROM companies c 
            LEFT JOIN company_documents d ON c.id = d.company_id 
            WHERE c.id = %s
            GROUP BY c.id
        """, (company_id,))
        
        company = cursor.fetchone()
        if not company:
            return jsonify({"success": False, "error": "Company not found"}), 404

        # Get company settings
        cursor.execute("""
            SELECT available_days, start_time, end_time 
            FROM company_settings 
            WHERE company_id = %s
        """, (company_id,))
        settings = cursor.fetchone()
        
        # Format settings for the system message
        settings_info = ""
        if settings:
            available_days = settings[0].split(',') if settings[0] else []
            start_time = settings[1]
            end_time = settings[2]
            
            settings_info = f"""
            Meeting Availability:
            - Available Days: {', '.join(available_days)}
            - Time Slot: {start_time} to {end_time}
            """
        else:
            settings_info = "No meeting settings configured yet."

        # Get website URLs
        cursor.execute("""
            SELECT url, page_title 
            FROM website_pages 
            WHERE company_id = %s
        """, (company_id,))
        available_urls = cursor.fetchall()
        
        # Format URLs
        url_context = "Available pages:\n"
        if available_urls:
            for url, title in available_urls:
                url_context += f"- {title}: {url}\n"
        else:
            url_context = f"Main website: {company[2]}\n"

        company_info = ""
        if company[1]:
            company_info += f"General Information:\n{company[1]}\n\n"
        
        if company[3]:
            company_info += f"Additional Information from Documents:\n{company[3]}\n\n"

        # Create system message with all information
        system_message = {
            "role": "system",
            "content": f"""You are a customer service representative for {company[0]}. 
            Keep your responses brief and professional.

            Company Information:
            {company_info}

            Website Information:
            {url_context}

            {settings_info}

            Meeting Scheduling Instructions:
            {create_meeting_prompt(company[0])}

            Guidelines:
            1. Use information from both the provided instructions and PDF documents to give accurate responses
            2. Keep responses concise and relevant
            3. If information is available in multiple sources, combine it appropriately
            4. For website-related queries, only use the URLs provided above
            5. If you don't have enough information to answer accurately, say so
            6. For meeting requests, strictly follow the meeting scheduling process
            7. If customer starts conversation with hello or similar greetings, respond briefly and ask how you can help
            8. Track meeting scheduling state and only proceed when all required information is collected
            9. When scheduling meetings, ensure the requested day and time are within the company's available slots
            10. If a customer requests a meeting outside available hours, inform them of the available slots
            11. You are both a text and voice-based agent - adapt your responses appropriately based on whether the user is typing or speaking
            
            When detecting a meeting request:
            Respond with both natural language and JSON action, as action is needed to store meeting details
            Format: [ACTION]{{"action": "schedule_meeting", "email": "...", "date": "...", "time": "..."}}[/ACTION]
            For the date field:
            - If the user provides a natural language date (e.g., "next Monday,Tomorrow"), use that exact phrase
            - If the user provides a specific date (e.g., "2024-03-20"), use that format
            - DO NOT include any additional text or formatting instructions in the date field
            Ensure the JSON inside [ACTION] tags is valid — use double quotes, include all commas, and no comments or extra text.
            """
        }

        # Store user message
        cursor.execute("""
            INSERT INTO chat_messages (
                id, company_id, role, content, 
                session_id, is_voice_input
            )
            VALUES (%s, %s, %s, %s, %s, %s)
        """, (
            str(uuid.uuid4()), company_id, 'user', 
            user_message, session_id, is_voice
        ))

        # Get chat history
        cursor.execute("""
            SELECT role, content 
            FROM chat_messages 
            WHERE company_id = %s AND session_id = %s 
            ORDER BY created_at ASC
        """, (company_id, session_id))
        
        chat_history = cursor.fetchall()
        
        # Construct messages array
        messages = [system_message]
        for role, content in chat_history:
            messages.append({"role": role, "content": content})

        # Call Groq API
        response = requests.post(
            Config.GROQ_API_URL,
            headers={
                "Authorization": f"Bearer {Config.GROQ_API_KEY}",
                "Content-Type": "application/json"
            },
            json={
                "model": "llama-3.3-70b-versatile",
                "messages": messages,
                "temperature": 1,
                "max_tokens": 1000,
                "top_p": 1,
                "stream": False
            }
        )
        
        if response.status_code == 200:
            ai_response = response.json()["choices"][0]["message"]["content"]

            # Check for meeting scheduling action
            action_pattern = re.compile(r'\[ACTION\](.*?)\[/ACTION\]', re.DOTALL)
            action_match = action_pattern.search(ai_response)

            if action_match:
                try:
                    action_data = json.loads(action_match.group(1))
                    if action_data.get('action') == 'schedule_meeting':
                        # Clean up the date field if it contains extra text
                        if 'date' in action_data:
                            date_str = action_data['date']
                            # Remove any text in parentheses or after them
                            date_str = re.sub(r'\s*\(.*?\)\s*', '', date_str)
                            # Remove any "date" or "date is" text
                            date_str = re.sub(r'\s*date\s*(is)?\s*', '', date_str, flags=re.IGNORECASE)
                            action_data['date'] = date_str.strip()
                        
                        print(f"before calling the function: {action_data}")
                        meeting_response = schedule_meeting(company_id, action_data)
                        if isinstance(meeting_response, tuple):
                            meeting_data = meeting_response[0].get_json()
                        else:
                            meeting_data = meeting_response.get_json()
                        if meeting_data.get('success'):
                            ai_response = meeting_data.get('message', 'Meeting scheduled successfully!')
                        else:
                            ai_response = meeting_data.get('error', 'Failed to schedule meeting. Please try again.')
                except Exception as e:
                    print(f"exception part: {action_data}")
                    ai_response = f"Error scheduling meeting: {str(e)}"

            # Store AI response
            cursor.execute("""
                INSERT INTO chat_messages (
                    id, company_id, role, content, 
                    session_id, is_voice_input
                )
                VALUES (%s, %s, %s, %s, %s, %s)
            """, (
                str(uuid.uuid4()), company_id, 'assistant', 
                ai_response, session_id, is_voice
            ))
            
            mysql.connection.commit()
            
            return jsonify({
                "success": True,
                "response": ai_response,
                "session_id": session_id,
                "should_speak": is_voice
            })
        else:
            return jsonify({"success": False, "error": "Failed to get AI response"}), 500
            
    except Exception as e:
        print(f"Error in company_chat: {str(e)}")
        return jsonify({"success": False, "error": str(e)}), 500


@api_bp.route('/api/<company_id>/schedule-meeting', methods=['POST'])
def schedule_meeting(company_id, meeting_data=None):
    try:
        if not meeting_data:
            if not request.is_json:
                return jsonify({"success": False, "error": "Request must be JSON"}), 400

            meeting_data = request.get_json()
            if not meeting_data:
                return jsonify({"success": False, "error": "No JSON data received"}), 400

        required_fields = ['email', 'date', 'time']
        
        for field in required_fields:
            if field not in meeting_data:
                return jsonify({"success": False, "error": f"Missing required field: {field}"}), 400

        cursor = mysql.connection.cursor()
        cursor.execute("""
            SELECT available_days, start_time, end_time 
            FROM company_settings 
            WHERE company_id = %s
        """, (company_id,))
        settings = cursor.fetchone()
        
        if not settings:
            return jsonify({"success": False, "error": "Company has not configured meeting availability settings"}), 400

        try:
            # Parse the date using our natural date parser
            date_result = parse_natural_date(meeting_data['date'])
            if not date_result:
                return jsonify({"success": False, "error": f"Could not parse date: {meeting_data['date']}"}), 400
                
            meeting_date = date_result['iso_date']
            meeting_time = meeting_data['time']
            # Ensure meeting_date is a string
            if not isinstance(meeting_date, str):
                logger.error(f"meeting_date is not a string: {type(meeting_date)}")
                return jsonify({"success": False, "error": "Invalid date format"}), 400
            
            # Create datetime object from the parsed date and time
            try:
                meeting_datetime = datetime.strptime(f"{meeting_date} {meeting_time}", "%Y-%m-%d %H:%M")
                logger.debug(f"Successfully created datetime object: {meeting_datetime}")
            except Exception as e:
                logger.error(f"Error creating datetime object: {str(e)}")
                return jsonify({"success": False, "error": f"Invalid date/time format: {str(e)}"}), 400
            
            day_name = meeting_datetime.strftime("%A")
            
            available_days = settings[0].split(',') if settings[0] else []
            
            # Convert timedelta to string in HH:MM format
            def timedelta_to_str(td):
                total_seconds = int(td.total_seconds())
                hours, remainder = divmod(total_seconds, 3600)
                minutes, _ = divmod(remainder, 60)
                return f"{hours:02}:{minutes:02}"
            
            # Parse time strings into time objects
            try:
                # Convert settings times to strings if they're timedelta
                start_time_str = timedelta_to_str(settings[1]) if isinstance(settings[1], timedelta) else settings[1]
                end_time_str = timedelta_to_str(settings[2]) if isinstance(settings[2], timedelta) else settings[2]
                
                # Parse the time strings
                start_time = datetime.strptime(start_time_str, "%H:%M").time()
                end_time = datetime.strptime(end_time_str, "%H:%M").time()
                meeting_time_obj = datetime.strptime(meeting_time, "%H:%M").time()
            except Exception as e:
                logger.error(f"Error parsing time objects: {str(e)}")
                return jsonify({"success": False, "error": f"Invalid time format: {str(e)}"}), 400
            
            if day_name not in available_days:
                return jsonify({"success": False, "error": f"Meetings are not available on {day_name}. Available days are: {', '.join(available_days)}"}), 400
            
            if not (start_time <= meeting_time_obj <= end_time):
                return jsonify({"success": False, "error": f"Meeting time must be between {start_time_str} and {end_time_str}"}), 400
            
        except Exception as e:
            logger.error(f"Error parsing datetime: {str(e)}")
            return jsonify({"success": False, "error": f"Invalid date/time format: {str(e)}"}), 400

        try:
            cursor.execute("""
                INSERT INTO meetings (id, company_id, customer_email, meeting_date, meeting_time)
                VALUES (%s, %s, %s, %s, %s)
            """, (
                uuid.uuid4(),
                company_id,
                meeting_data['email'],
                meeting_date,
                meeting_time
            ))
            mysql.connection.commit()
        except Exception as e:
            logger.error(f"Database error: {str(e)}")
            return jsonify({"success": False, "error": f"Database error: {str(e)}"}), 500

        email_subject = "Meeting Scheduled Confirmation"
        
        cursor.execute("SELECT name FROM companies WHERE id = %s", (company_id,))
        company_result = cursor.fetchone()
        company_name = company_result[0] if company_result else "Company"

        cursor.execute("SELECT email FROM companies WHERE id = %s", (company_id,))
        company_email_result = cursor.fetchone()
        company_email = company_email_result[0] if company_email_result else "info@mykaptaan.com"

        send_email(
            to_email=meeting_data['email'],
            subject=email_subject,
            date=meeting_date,
            time=meeting_time,
            company_name=company_name,
            company_email=company_email,
            customer_email=meeting_data['email']
        )

        return jsonify({"success": True, "message": f"Meeting scheduled on {meeting_date} at {meeting_time}"})

    except Exception as e:
        logger.error(f"Error scheduling meeting: {str(e)}")
        return jsonify({"success": False, "error": str(e)}), 500
    
@api_bp.route('/api/<company_id>/chat-history', methods=['GET'])
def get_chat_history(company_id):
    try:
        session_id = request.args.get('session_id')
        if not session_id:
            return jsonify({"success": False, "error": "Session ID is required"}), 400

        cursor = mysql.connection.cursor()
        
        # Get chat history for this session
        cursor.execute("""
            SELECT role, content, created_at 
            FROM chat_messages 
            WHERE company_id = %s AND session_id = %s 
            ORDER BY created_at ASC
        """, (company_id, session_id))
        
        messages = cursor.fetchall()
        
        # Format messages for response
        history = [
            {
                "role": msg[0],
                "content": msg[1],
                "timestamp": msg[2].isoformat() if msg[2] else None
            }
            for msg in messages
        ]
        
        return jsonify({
            "success": True,
            "history": history
        })
        
    except Exception as e:
        print(f"Error fetching chat history: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@api_bp.route('/api/<company_id>/refresh-urls', methods=['POST'])
def refresh_company_urls(company_id):
    try:
        cursor = mysql.connection.cursor()
        
        # Get website URL from request
        website_url = request.json.get('websiteUrl')
        if not website_url:
            return jsonify({"success": False, "error": "Website URL is required"}), 400
            
        # Update company website
        cursor.execute("UPDATE companies SET website = %s WHERE id = %s", (website_url, company_id))
        
        if website_url.startswith('@'):
            website_url = website_url[1:]
            
        print(f"Refreshing URLs for website: {website_url}")  # Debug log
        
        # Clear existing pages
        cursor.execute("DELETE FROM website_pages WHERE company_id = %s", (company_id,))
        
        # Crawl and store new links
        links = get_website_content(website_url)
        stored_count = 0
        
        for link in links:
            try:
                cursor.execute("""
                    INSERT INTO website_pages (id, company_id, url, page_title)
                    VALUES (%s, %s, %s, %s)
                """, (str(uuid.uuid4()), company_id, link['url'], link['text']))
                stored_count += 1
            except Exception as e:
                print(f"Error storing URL: {str(e)}")
        
        mysql.connection.commit()
        print(f"Successfully stored {stored_count} URLs")  # Debug log
        
        return jsonify({
            "success": True,
            "message": f"Stored {stored_count} URLs",
            "urls": [link['url'] for link in links]
        })
        
    except Exception as e:
        print(f"Error refreshing URLs: {str(e)}")
        return jsonify({"success": False, "error": str(e)}), 500


def extract_meeting_info(message):
    # Extract email using regex
    email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
    email_match = re.search(email_pattern, message)
    email = email_match.group(0) if email_match else None
    
    # Extract date (assuming format YYYY-MM-DD)
    date_pattern = r'\d{4}-\d{2}-\d{2}'
    date_match = re.search(date_pattern, message)
    date = date_match.group(0) if date_match else None
    
    # Extract time (assuming format HH:MM)
    time_pattern = r'\d{2}:\d{2}'
    time_match = re.search(time_pattern, message)
    time = time_match.group(0) if time_match else None
    
    return email, date, time

def send_email(to_email, subject, date, time, company_name, company_email, customer_email):
    start_date, end_date = format_google_calendar_date(date, time)
    html_content = render_template(
        'email_template/meeting.html',
        date=date,
        time=time,
        company_name=company_name,
        start_date=start_date,
        end_date=end_date,
        company_email=company_email,
        customer_email=customer_email
    )
    msg = MIMEMultipart()
    msg['From'] = Config.SMTP_USER
    msg['To'] = to_email
    msg['Subject'] = subject

    # Attach the HTML content
    msg.attach(MIMEText(html_content, 'html'))

    # Use SMTP_SSL for secure connection
    with smtplib.SMTP_SSL(Config.SMTP_SERVER, Config.SMTP_PORT, timeout=20) as server:
        server.login(Config.SMTP_USER, Config.SMTP_PASSWORD)
        server.send_message(msg)

    print(f"Email sent to {to_email}")


def format_google_calendar_date(date_str, time_str):
    dt = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M")
    start_date = dt.strftime("%Y%m%dT%H%M%SZ")
    end_date = (dt + timedelta(hours=1)).strftime("%Y%m%dT%H%M%SZ")  # Assuming 1-hour meeting
    return start_date, end_date

@api_bp.route('/api/<company_id>/widget-settings')
def get_widget_settings(company_id):
    cursor = mysql.connection.cursor()
    cursor.execute("""
        SELECT widget_color, voice_speed 
        FROM company_settings 
        WHERE company_id = %s
    """, (company_id,))
    settings = cursor.fetchone()
    cursor.close()
    return jsonify({
        "success": True,
        "settings": settings if settings else {
            "widget_color": "#F42941",
            "voice_speed": "1.0"
        }
    })

@api_bp.route('/api/<company_id>/fetch-chats', methods=['GET'])
@require_basic_auth
def api_chat_history(company_id):
    try:
        cursor = mysql.connection.cursor()
        
        # Get all sessions for the company
        cursor.execute("""
            SELECT 
                cm.session_id,
                MIN(CASE WHEN cm.role = 'user' THEN cm.content END) as first_message,
                MAX(cm.created_at) as last_message_time,
                COUNT(*) as message_count
            FROM chat_messages cm
            WHERE cm.company_id = %s
            GROUP BY cm.session_id
            ORDER BY last_message_time DESC
        """, (company_id,))
        
        chat_sessions = cursor.fetchall()
        formatted_sessions = []

        # For each session, get its messages
        for session_data in chat_sessions:
            session_id = session_data[0]
            cursor.execute("""
                SELECT role, content, created_at
                FROM chat_messages
                WHERE company_id = %s AND session_id = %s
                ORDER BY created_at ASC
            """, (company_id, session_id))
            messages = cursor.fetchall()
            formatted_messages = [
                {
                    'role': msg[0],
                    'content': msg[1],
                    'created_at': msg[2].isoformat() if hasattr(msg[2], 'isoformat') else str(msg[2])
                }
                for msg in messages
            ]
            formatted_sessions.append({
                'session_id': session_id,
                'first_message': session_data[1],
                'last_message_time': session_data[2].isoformat() if hasattr(session_data[2], 'isoformat') else str(session_data[2]),
                'message_count': session_data[3],
                'messages': formatted_messages
            })
        
        return jsonify({
            "success": True,
            "chat_sessions": formatted_sessions
        })
        
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500
    
@api_bp.route('/api/<company_id>/fetch-meetings', methods=['GET'])
@require_basic_auth
def api_meetings(company_id):
    try:
        cursor = mysql.connection.cursor()
        cursor.execute("""
            SELECT 
                id,
                customer_email,
                meeting_date,
                meeting_time
            FROM meetings 
            WHERE company_id = %s 
            ORDER BY meeting_date DESC
        """, (company_id,))
        
        meetings = cursor.fetchall()
        formatted_meetings = [
            {
                'id': m[0],
                'customer_email': m[1],
                'meeting_date': m[2].isoformat() if hasattr(m[2], 'isoformat') else str(m[2]),
                'meeting_time': str(m[3])
            }
            for m in meetings
        ]
        
        return jsonify({
            "success": True,
            "meetings": formatted_meetings
        })
        
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500