import frappe
from erpnext.selling.doctype.quotation.quotation import make_sales_order
from custom_ui.services import DbService, AddressService, ClientService

def after_insert(doc, method):
    print("DEBUG: After insert hook triggered for Quotation:", doc.name)
    AddressService.append_link_v2(
        doc.custom_job_address, "quotations", {"quotation": doc.name, "project_template": doc.custom_project_template}
    )
    AddressService.append_link_v2(
        doc.custom_job_address, "links", {"link_doctype": "Quotation", "link_name": doc.name}
    )
    ClientService.append_link_v2(
        doc.actual_customer_name, "quotations", {"quotation": doc.name, "project_template": doc.custom_project_template}
    )
    template = doc.custom_project_template or "Other"
    if template == "Other":
        print("WARN: No project template specified.")
    if template == "SNW Install":
        print("DEBUG: SNW Install template detected, updating custom address field.")
        AddressService.update_value(
            doc.custom_job_address,
            "estimate_sent_status",
            "In Progress"
        )
        
def before_insert(doc, method):
    print("DEBUG: Before insert hook triggered for Quotation:", doc)
    print("DEBUG: CHECKING CUSTOMER TYPE")
    print(doc.customer_type)
    print("DEBUG: CHECKING CUSTOMER NAME")
    print(doc.actual_customer_name)
    print("Quotation_to:", doc.quotation_to)
    doc.customer_address = frappe.get_value(doc.customer_type, doc.actual_customer_name, "custom_billing_address")
    # print("Party_type:", doc.party_type)
    if doc.custom_project_template == "SNW Install":
        print("DEBUG: Quotation uses SNW Install template, making sure no duplicate linked estimates.")
        address_doc = AddressService.get_or_throw(doc.custom_job_address)
        # if "SNW Install" in [link.project_template for link in address_doc.quotations]:
            # raise frappe.ValidationError("An Estimate with project template 'SNW Install' is already linked to this address.")

def before_submit(doc, method):
    print("DEBUG: Before submit hook triggered for Quotation:", doc.name)
    if doc.custom_project_template == "SNW Install":
        print("DEBUG: Quotation uses SNW Install template.")
        if doc.custom_sent == 1:
            print("DEBUG: Current status is 'Estimate Sent', updating Address status to 'Sent'.")
            AddressService.update_value(
                doc.custom_job_address,
                "estimate_sent_status",
                "Completed"
            )

def on_update_after_submit(doc, method):
    print("DEBUG: on_update_after_submit hook triggered for Quotation:", doc.name)
    print("DEBUG: Current custom_current_status:", doc.custom_current_status)
    if doc.custom_current_status == "Won":
        print("DEBUG: Quotation is already marked as Won, no action needed.")
        return
    if doc.custom_current_status == "Estimate Accepted":
        doc.custom_current_status = "Won"
        print("DEBUG: Quotation marked as Won, updating current status.")
        if doc.customer_type == "Lead":
            print("DEBUG: Customer is a Lead, converting to Customer and updating Quotation.")
            new_customer = ClientService.convert_lead_to_customer(doc.actual_customer_name)
            doc.customer_type = "Customer"
            doc.actual_customer_name = new_customer.name
            new_customer.reload()
            doc.save()
        print("DEBUG: Creating Sales Order from accepted Estimate")
        new_sales_order = make_sales_order(doc.name)
        new_sales_order.requires_half_payment = doc.requires_half_payment
        new_sales_order.customer = doc.actual_customer_name
        new_sales_order.customer_name = doc.actual_customer_name
        new_sales_order.customer_address = doc.customer_address
        # new_sales_order.custom_installation_address = doc.custom_installation_address
        new_sales_order.custom_job_address = doc.custom_job_address
        new_sales_order.payment_schedule = []
        print("DEBUG: Setting payment schedule for Sales Order")
        new_sales_order.set_payment_schedule()
        print("DEBUG: Inserting Sales Order:", new_sales_order.as_dict())
        new_sales_order.delivery_date = new_sales_order.transaction_date
        # backup = new_sales_order.customer_address
        # new_sales_order.customer_address = None
        new_sales_order.insert()
        print("DEBUG: Submitting Sales Order")
        # new_sales_order.customer_address = backup
        new_sales_order.submit()
        # frappe.db.commit()
        print("DEBUG: Sales Order created successfully:", new_sales_order.name)
