import frappe
import json
from custom_ui.models import PackageCreationData
from custom_ui.services import ProjectService, ItemService
from custom_ui.db_utils import build_error_response, build_success_response


@frappe.whitelist()
def get_by_project_template(project_template: str) -> dict:
    """Retrieve items associated with a given project template."""
    print(f"DEBUG: Getting items for Project Template {project_template}")
    item_groups = ProjectService.get_project_item_groups(project_template)
    items = ItemService.get_items_by_groups(item_groups)
    print(f"DEBUG: Retrieved {len(items)} items for Project Template {project_template}")
    categorized_items = ItemService.build_category_dict(items)
    return build_success_response(categorized_items)

@frappe.whitelist()
def save_as_package_item(data):
    """Save a new Package Item based on the provided data."""
    from custom_ui.models import BOMItem
    data = json.loads(data)
    print(f"DEBUG: Saving Package Item with data: {data}")
    # Map 'category' to 'item_group' for the model
    data['item_group'] = data.pop('category')
    # Convert items dictionaries to BOMItem instances
    data['items'] = [
        BOMItem(
            item_code=item['item_code'],
            qty=item['qty'],
            uom=item['uom']
        ) for item in data['items']
    ]
    data = PackageCreationData(**data)
    item = frappe.get_doc({
        "doctype": "Item",
        "item_code": ItemService.build_item_code(data.code_prefix, data.package_name),
        "item_name": data.package_name,
        "is_stock_item": 0,
        "item_group": data.item_group,
        "description": data.description,
        "standard_rate": data.rate or 0.0,
        "company": data.company,
        "has_variants": 0,
        "stock_uom": "Nos",
        "is_sales_item": 1,
        "is_purchase_item": 0,
        "is_pro_applicable": 0,
        "is_fixed_asset": 0,
        "is_service_item": 0
    }).insert()
    bom = frappe.get_doc({
        "doctype": "BOM",
        "item": item.name,
        "uom": "Nos",
        "is_active": 1,
        "is_default": 1,
        "items": [{
            "item_code": bom_item.item_code,
            "qty": bom_item.qty,
            "uom": bom_item.uom
        } for bom_item in data.items]
    }).insert()
    bom.submit()
    item.reload()  # Refresh to get latest version after BOM submission
    item.default_bom = bom.name
    item.save()
    print(f"DEBUG: Created Package Item with name: {item.name}")
    item_dict = item.as_dict()
    item_dict["bom"] = ItemService.get_full_bom_dict(item.item_code)  # Attach BOM details to the item dict    
    return build_success_response(item_dict)

@frappe.whitelist()
def get_item_categories():
    """Retrieve all item groups for categorization."""
    print("DEBUG: Getting item categories")
    item_groups = frappe.get_all("Item Group", pluck="name")
    print(f"DEBUG: Retrieved item categories: {item_groups}")
    return build_success_response(item_groups)

