"""
Appointment Service Layer

This module provides services for managing appointments without relying on API calls.
It can be easily extended to support database or CRM integration in the future.
"""

import os
import json
import uuid
import logging
from datetime import datetime
from typing import Dict, Any, Optional, List

# Set up logger
logger = logging.getLogger("mango_ai_agent")

# File path for storing appointments
APPOINTMENTS_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "appointments.json")

# Ensure the data directory exists
os.makedirs(os.path.dirname(APPOINTMENTS_FILE), exist_ok=True)

# In-memory cache of appointments
_appointments_cache: Dict[str, Dict[str, Any]] = {}
_cache_loaded = False


def _load_appointments() -> Dict[str, Dict[str, Any]]:
    """Load appointments from file"""
    global _appointments_cache, _cache_loaded
    
    if _cache_loaded:
        return _appointments_cache
    
    try:
        if os.path.exists(APPOINTMENTS_FILE):
            with open(APPOINTMENTS_FILE, "r") as f:
                _appointments_cache = json.load(f)
                logger.info(f"Loaded {len(_appointments_cache)} appointments from file")
        else:
            _appointments_cache = {}
            logger.info("No appointments file found, starting with empty appointments")
    except Exception as e:
        logger.error(f"Error loading appointments: {str(e)}")
        _appointments_cache = {}
    
    _cache_loaded = True
    return _appointments_cache


def _save_appointments() -> bool:
    """Save appointments to file"""
    try:
        with open(APPOINTMENTS_FILE, "w") as f:
            json.dump(_appointments_cache, f, indent=2)
        logger.info(f"Saved {len(_appointments_cache)} appointments to file")
        return True
    except Exception as e:
        logger.error(f"Error saving appointments: {str(e)}")
        return False


def create_appointment(appointment_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    Create a new appointment
    
    Args:
        appointment_data: Dictionary containing appointment information
        
    Returns:
        Dict[str, Any]: The created appointment with ID
    """
    # Load appointments if not already loaded
    appointments = _load_appointments()
    
    # Generate a unique ID for the appointment
    appointment_id = str(uuid.uuid4())
    
    # Create the appointment object
    appointment = {
        **appointment_data,
        "appointment_id": appointment_id,
        "status": "pending",
        "created_at": str(datetime.now())
    }
    
    # Store the appointment
    appointments[appointment_id] = appointment
    
    # Save appointments to file
    _save_appointments()
    
    logger.info(f"Created appointment with ID: {appointment_id}")
    
    return {
        "success": True,
        "appointment_id": appointment_id,
        "status": "pending",
        "message": "Appointment scheduled successfully",
        "method": "service_layer"
    }


def get_appointment(appointment_id: str) -> Optional[Dict[str, Any]]:
    """
    Get an appointment by ID
    
    Args:
        appointment_id: The appointment ID
        
    Returns:
        Optional[Dict[str, Any]]: The appointment or None if not found
    """
    appointments = _load_appointments()
    return appointments.get(appointment_id)


def get_appointments_by_conversation(conversation_id: str) -> List[Dict[str, Any]]:
    """
    Get all appointments for a conversation
    
    Args:
        conversation_id: The conversation ID
        
    Returns:
        List[Dict[str, Any]]: List of appointments for the conversation
    """
    appointments = _load_appointments()
    return [
        appointment for appointment in appointments.values()
        if appointment.get("conversation_id") == conversation_id
    ]


def update_appointment_status(appointment_id: str, status: str) -> bool:
    """
    Update the status of an appointment
    
    Args:
        appointment_id: The appointment ID
        status: The new status
        
    Returns:
        bool: True if successful, False otherwise
    """
    appointments = _load_appointments()
    
    if appointment_id not in appointments:
        logger.error(f"Appointment not found: {appointment_id}")
        return False
    
    appointments[appointment_id]["status"] = status
    appointments[appointment_id]["updated_at"] = str(datetime.now())
    
    _save_appointments()
    
    logger.info(f"Updated appointment {appointment_id} status to {status}")
    return True


def delete_appointment(appointment_id: str) -> bool:
    """
    Delete an appointment
    
    Args:
        appointment_id: The appointment ID
        
    Returns:
        bool: True if successful, False otherwise
    """
    appointments = _load_appointments()
    
    if appointment_id not in appointments:
        logger.error(f"Appointment not found: {appointment_id}")
        return False
    
    del appointments[appointment_id]
    
    _save_appointments()
    
    logger.info(f"Deleted appointment {appointment_id}")
    return True
