import frappe, json, re
from datetime import datetime, date
from custom_ui.db_utils import build_error_response, build_success_response, process_query_conditions, build_datatable_dict, get_count_or_filters

# ===============================================================================
# WARRANTY MANAGEMENT API METHODS
# ===============================================================================

@frappe.whitelist()
def get_warranty_claims(filters={}, sortings=[], page=1, page_size=10):
    """Get paginated warranty claims table data with filtering and sorting support."""
    try:
        print("DEBUG: Raw warranty options received:", filters, sortings, page, page_size)
        
        processed_filters, processed_sortings, is_or, page, page_size = process_query_conditions(filters, sortings, page, page_size)
        
        # Handle count with proper OR filter support
        if is_or:
            count = frappe.db.sql(*get_count_or_filters("Warranty Claim", processed_filters))[0][0]
        else:
            count = frappe.db.count("Warranty Claim", filters=processed_filters)
        
        warranty_claims = frappe.db.get_all(
            "Warranty Claim",
            fields=["*"],
            filters=processed_filters if not is_or else None,
            or_filters=processed_filters if is_or else None,
            limit=page_size,
            start=(page - 1) * page_size,
            order_by=processed_sortings
        )
        
        tableRows = []
        for warranty in warranty_claims:
            tableRow = {}
            tableRow["id"] = warranty["name"]
            tableRow["warrantyId"] = warranty["name"]
            tableRow["customer"] = warranty.get("customer_name", "")
            tableRow["serviceAddress"] = warranty.get("service_address", warranty.get("address_display", ""))

            # Extract a brief description from the complaint HTML
            complaint_text = warranty.get("complaint", "")
            if complaint_text:
                # Simple HTML stripping for display - take first 100 chars
                clean_text = re.sub('<.*?>', '', complaint_text)
                clean_text = clean_text.strip()
                if len(clean_text) > 100:
                    clean_text = clean_text[:100] + "..."
                tableRow["issueDescription"] = clean_text
            else:
                tableRow["issueDescription"] = ""

            tableRow["status"] = warranty.get("status", "")
            tableRow["complaintDate"] = warranty.get("complaint_date", "")
            tableRow["complaintRaisedBy"] = warranty.get("complaint_raised_by", "")
            tableRow["fromCompany"] = warranty.get("from_company", "")
            tableRow["territory"] = warranty.get("territory", "")
            tableRow["resolutionDate"] = warranty.get("resolution_date", "")
            tableRow["warrantyStatus"] = warranty.get("warranty_amc_status", "")

            # Add priority based on status and date (can be customized)
            if warranty.get("status") == "Open":
                # Calculate priority based on complaint date
                if warranty.get("complaint_date"):
                    complaint_date = warranty.get("complaint_date")
                    if isinstance(complaint_date, str):
                        complaint_date = datetime.strptime(complaint_date, "%Y-%m-%d").date()
                    elif isinstance(complaint_date, datetime):
                        complaint_date = complaint_date.date()

                    days_old = (date.today() - complaint_date).days
                    if days_old > 7:
                        tableRow["priority"] = "High"
                    elif days_old > 3:
                        tableRow["priority"] = "Medium"
                    else:
                        tableRow["priority"] = "Low"
                else:
                    tableRow["priority"] = "Medium"
            else:
                tableRow["priority"] = "Low"
            tableRows.append(tableRow)
        
        tableDataDict = build_datatable_dict(data=tableRows, count=count, page=page, page_size=page_size)
        return build_success_response(tableDataDict)
    except frappe.ValidationError as ve:
        return build_error_response(str(ve), 400)
    except Exception as e:
        return build_error_response(str(e), 500)


@frappe.whitelist()
def upsert_warranty(data):
    """Create or update a warranty claim."""
    # TODO: Implement warranty creation/update logic
    pass