import frappe
from custom_ui.db_utils import build_history_entries, build_success_response, build_error_response
from datetime import datetime, timedelta
import json

def get_doc_history(doctype, docname):
    """Get the history of changes for a specific document."""
    # Fetch comments
    comments = frappe.get_all(
        "Comment",
        filters={
            "reference_doctype": doctype,
            "reference_name": docname
        },
        fields=["*"],
        order_by="creation desc"
    )
    versions = frappe.get_all(
        "Version",
        filters={"docname": docname, "ref_doctype": doctype},
        fields=["*"],
        order_by="creation desc"
    )
    history_entries = build_history_entries(comments, versions)
    print(f"DEBUG: Retrieved history for {doctype} {docname}: {history_entries}")
    return history_entries

def get_docs_history(doctypes_with_names):
    """Get history for multiple documents."""
    all_history = {}
    for doctype, docname in doctypes_with_names:
        history = get_doc_history(doctype, docname)
        all_history[f"{doctype}:{docname}"] = history
    return all_history
        
def search_any_field(doctype, text):
    meta = frappe.get_meta(doctype)
    like = f"%{text}%"

    conditions = []

    # 1️⃣ Explicitly include `name`
    conditions.append("`name` LIKE %s")

    # 2️⃣ Include searchable DocFields
    for field in meta.fields:
        if field.fieldtype in ("Data", "Small Text", "Text", "Link"):
            conditions.append(f"`{field.fieldname}` LIKE %s")

    query = f"""
        SELECT name
        FROM `tab{doctype}`
        WHERE {" OR ".join(conditions)}
        LIMIT 20
    """

    return frappe.db.sql(
        query,
        [like] * len(conditions),
        as_dict=True
    )
    
@frappe.whitelist()
def get_week_holidays(week_start_date: str):
    """Get holidays within a week starting from the given date."""

    start_date = datetime.strptime(week_start_date, "%Y-%m-%d").date()
    end_date = start_date + timedelta(days=6)

    holidays = frappe.get_all(
        "Holiday",
        filters={
            "holiday_date": ["between", (start_date, end_date)]
        },
        fields=["holiday_date", "description"],
        order_by="holiday_date asc"
    )

    print(f"DEBUG: Retrieved holidays from {start_date} to {end_date}: {holidays}")
    return build_success_response(holidays)

@frappe.whitelist()
def get_doc_list(doctype, fields=["*"], filters={}, pluck=None):
    """Get list of documents for a given doctype with specified fields and filters."""
    if isinstance(fields, str):
        fields = json.loads(fields)
    if isinstance(filters, str):
        filters = json.loads(filters)
    try:
        docs = frappe.get_all(
            doctype,
            fields=fields,
            filters=filters,
            order_by="creation desc",
            # pluck=pluck
        )
        print(f"DEBUG: Retrieved documents for {doctype} with filters {filters}: {docs}")
        return build_success_response(docs)
    except Exception as e:
        return build_error_response(str(e), 500)