import frappe
from custom_ui.services import TaskService, AddressService

class ProjectService:
    
    @staticmethod
    def get_project_item_groups(project_template: str) -> list[str]:
        """Retrieve item groups associated with a given project template."""
        print(f"DEBUG: Getting item groups for Project Template {project_template}")
        item_groups_str = frappe.db.get_value("Project Template", project_template, "item_groups") or ""
        item_groups = [item_group.strip() for item_group in item_groups_str.split(",") if item_group.strip()]
        print(f"DEBUG: Retrieved item groups: {item_groups}")
        return item_groups
    
    @staticmethod
    def get_full_project_details(project_name: str) -> dict:
        """Retrieve comprehensive details for a given project, including linked sales order and invoice information."""
        print(f"DEBUG: Getting full project details for project: {project_name}")
        project = frappe.get_doc("Project", project_name).as_dict()
        project["tasks"] = [frappe.get_doc("Task", task["task"]).as_dict() for task in project["tasks"] if task.get("task")]
        for task in project["tasks"]:
            task["type"] = frappe.get_doc("Task Type", task["type"]).as_dict() if task.get("type") else None
        project["job_address"] = frappe.get_doc("Address", project["job_address"]).as_dict() if project["job_address"] else None
        project["service_appointment"] = frappe.get_doc("Service Address 2", project["service_appointment"]).as_dict() if project["service_appointment"] else None
        project["client"] = frappe.get_doc("Customer", project["customer"]).as_dict() if project["customer"] else None
        project["sales_order"] = frappe.get_doc("Sales Order", project["sales_order"]).as_dict() if project["sales_order"] else None
        project["billing_address"] = frappe.get_doc("Address", project["client"]["custom_billing_address"]).as_dict() if project["client"] and project["client"].get("custom_billing_address") else None
        project["invoice"] = frappe.get_doc("Sales Invoice", {"project": project["name"]}).as_dict() if frappe.db.exists("Sales Invoice", {"project": project["name"]}) else None
        return project