import frappe, json
from custom_ui.db_utils import build_success_response, build_error_response
from custom_ui.services import ServiceAppointmentService

@frappe.whitelist()
def get_service_appointment(service_appointment_name):
    """Get a single Service Appointment by name."""
    try:
        service_appointment = ServiceAppointmentService.get_full_dict(service_appointment_name)
        return build_success_response(service_appointment)
    except Exception as e:
        return build_error_response(str(e), 500)

@frappe.whitelist()
def get_service_appointments(companies, filters={}):
    """Get Service Appointments for given companies."""
    try:
        if isinstance(companies, str):
            companies = json.loads(companies)
        if isinstance(filters, str):
            filters = json.loads(filters)
        filters["company"] = ["in", companies]
        service_appointment_names = frappe.get_all(
            "Service Address 2",
            filters=filters,
            pluck="name"
        )
        service_appointments = [
            ServiceAppointmentService.get_full_dict(name)
            for name in service_appointment_names
        ]
        
        "is_half_down_paid"
        
        return build_success_response(service_appointments)
    except Exception as e:
        return build_error_response(str(e), 500)
    
@frappe.whitelist()
def get_unscheduled_service_appointments(companies):
    """Get unscheduled Service Appointments for given companies."""
    try:
        if isinstance(companies, str):
            companies = json.loads(companies)
        filters = {
            "company": ["in", companies],
            "expected_start_date": None,
            "status": "Open"
        }
        service_appointment_names = frappe.get_all(
            "Service Address 2",
            filters=filters,
            pluck="name"
        )
        service_appointments = [
            ServiceAppointmentService.get_full_dict(name)
            for name in service_appointment_names
        ]
        return build_success_response(service_appointments)
    except Exception as e:
        return build_error_response(str(e), 500)
    
@frappe.whitelist()
def update_service_appointment_scheduled_dates(service_appointment_name: str, start_date, end_date, crew_lead_name, start_time=None, end_time=None):
    """Update scheduled dates for a Service Appointment."""
    print(f"DEBUG: Updating scheduled dates for Service Appointment {service_appointment_name} to start: {start_date}, end: {end_date}, crew lead: {crew_lead_name}, start time: {start_time}, end time: {end_time}")
    try:
        updated_service_appointment = ServiceAppointmentService.update_scheduled_dates(
            service_appointment_name,
            crew_lead_name,
            start_date,
            end_date,
            start_time,
            end_time
        )
        return build_success_response(updated_service_appointment.as_dict())
    except Exception as e:
        return build_error_response(str(e), 500)
    

@frappe.whitelist()
def update_service_appointment_status(service_appointment_name: str, new_status: str):
    """Update status for a Service Appointment."""
    print(f"DEBUG: Updating status for Service Appointment {service_appointment_name} to new status: {new_status}")
    try:
        updated_service_appointment = ServiceAppointmentService.update_status(
            service_appointment_name,
            new_status
        )
        return build_success_response(updated_service_appointment.as_dict())
    except Exception as e:
        return build_error_response(str(e), 500)