import frappe
from custom_ui.services import AddressService, ClientService, TaskService

def before_insert(doc, method):
    """Set values before inserting a Task."""
    print("DEBUG: Before Insert Triggered for Task")
    project_doc = frappe.get_doc("Project", doc.project)
    doc.project_template = project_doc.project_template
    doc.customer = project_doc.customer
    if project_doc.job_address:
        doc.custom_property = project_doc.job_address

def after_insert(doc, method):
    print("DEBUG: After Insert Triggered for Task")
    print("DEBUG: Linking Task to Customer and Address")
    AddressService.append_link_v2(
        doc.custom_property, "tasks", {"task": doc.name, "project_template": doc.project_template }
    )
    AddressService.append_link_v2(
        doc.custom_property, "links", {"link_doctype": "Task", "link_name": doc.name}
    )
    ClientService.append_link_v2(
        doc.customer, "tasks", {"task": doc.name, "project_template": doc.project_template }
    )
    task_names = [task.name for task in TaskService.get_tasks_by_project(doc.project)]
    TaskService.fire_task_triggers(task_names, "Created", current_triggering_dict=doc.as_dict())
    
def before_save(doc, method):
    print("DEBUG: Before Save Triggered for Task:", doc.name)
    task_type_weight = frappe.get_value("Task Type", doc.type, "weight") or 0
    if doc.task_weight != task_type_weight:
        print(f"DEBUG: Updating Task weight from {doc.task_weight} to {task_type_weight}")
        doc.task_weight = task_type_weight
    event = TaskService.determine_event(doc)
    if event:
        task_names = [task.name for task in TaskService.get_tasks_by_project(doc.project)]
        TaskService.fire_task_triggers(task_names, event, current_triggering_dict=doc.as_dict())
    
def after_save(doc, method):
    print("DEBUG: After Save Triggered for Task:", doc.name)
    if doc.project and doc.status == "Completed":
        print("DEBUG: Task is completed, checking if project has calculated 100% Progress.")
        project_doc = frappe.get_doc("Project", doc.project)
        if project_doc.percent_complete == 100:
            project_update_required = False
            if project_doc.status == "Completed" and project_doc.customCompletionDate is None:
                print("DEBUG: Project is marked as Completed but customCompletionDate is not set, updating customCompletionDate.")
                project_doc.customCompletionDate = frappe.utils.nowdate()
                project_update_required = True
            if project_doc.invoice_status == "Not Ready":
                project_doc.invoice_status = "Ready to Invoice"
                project_update_required = True
            if project_update_required:
                project_doc.save(ignore_permissions=True)
                print("DEBUG: Updated Project document after Task completion")