import click
import os
import subprocess
import frappe
from custom_ui.utils import create_module
from custom_ui.api.db.general import search_any_field

@click.command("update-data")
@click.option("--site", default=None, help="Site to update data for")
def update_data(site):
    address_names = frappe.get_all("Address", pluck="name")
    total_addresses = len(address_names)
    updated_addresses = 0
    updated_contacts = 0
    updated_customers = 0
    total_updated_fields = 0
    skipped = 0
    for address_name in address_names:
        should_update = False
        address = frappe.get_doc("Address", address_name)
        customer_name = address.custom_customer_to_bill
        customer_links = [link for link in address.get("links", []) if link.link_doctype == "Customer"]
        # lead_links = [link for link in address.get("links", []) if link.link_doctype == "Lead"]
        contact_links = [link for link in address.get("links", []) if link.link_doctype == "Contact"] + address.get("custom_linked_contacts", [])
        
        if frappe.db.exists("Customer", customer_name):
            customer = frappe.get_doc("Customer", customer_name)
        else:
            lead_names = frappe.get_all("Lead", filters={"lead_name": customer_name}, pluck="name")
            customer_name = lead_names[0] if lead_names else None
            customer = frappe.get_doc("Lead", customer_name) if customer_name else None
        if not customer_links and customer and customer.doctype == "Customer":
            address.append("links", {
                "link_doctype": customer.doctype,
                "link_name": customer.name
            })
            updated_addresses += 1
            should_update = True
        elif not lead_links and customer and customer.doctype == "Lead":
            address.append("links", {
                "link_doctype": customer.doctype,
                "link_name": customer.name
            })
            updated_addresses += 1
            should_update = True
            
        
        
    
    

@click.command("build-frontend")
@click.option("--site", default=None, help="Site to build frontend for")
def build_frontend(site):
    app_package_path = frappe.get_app_path("custom_ui")
    app_root = os.path.dirname(app_package_path)

    candidates = [
        os.path.join(app_root, 'frontend'),
        os.path.join(app_package_path, 'frontend')
    ]

    frontend_path = None
    for p in candidates:
        if os.path.exists(p):
            frontend_path = p
            break

    if frontend_path:
        click.echo("\n📦 Building frontend for custom_ui...\n")
        try:
            subprocess.check_call(["npm", "install"], cwd=frontend_path)
            subprocess.check_call(["npm", "run", "build"], cwd=frontend_path)
            click.echo("\n✅ Frontend build completed successfully.\n")
        except subprocess.CalledProcessError as e:
            click.echo(f"\n❌ Frontend build failed: {e}\n")
            exit(1)
    else:
        frappe.log_error(message="No frontend directory found for custom_ui", title="Frontend Build Skipped")
        click.echo(f"\n⚠️ Frontend directory does not exist. Skipping build. Path was {frontend_path}\n")
    if not site:
        return
    try:
        print(f"\n🧹 Clearing cache for site {site}...\n")
        subprocess.check_call(["bench", "--site", site, "clear-cache"])
        subprocess.check_call(["bench", "--site", site, "clear-website-cache"])
    except subprocess.CalledProcessError as e:
        frappe.log_error(message=str(e), title="Clear Cache Failed")
        print(f"\n❌ Clearing cache failed: {e}\n")

    # Restart bench
    try:
        print("\n🔄 Restarting bench...\n")
        subprocess.check_call(["bench", "restart"])
    except subprocess.CalledProcessError as e:
        frappe.log_error(message=str(e), title="Bench Restart Failed")
        print(f"\n❌ Bench restart failed: {e}\n")

@click.command("create-module")
def create_module_command():
    create_module()
    click.echo("✅ Custom UI module created or already exists.")

commands = [build_frontend, create_module_command]