#!/usr/bin/env python3
"""Import print format HTML templates into ERPNext as Print Format records."""

import frappe
import os

TEMPLATE_DIR = "/home/frappe/erpnext-bench/apps/westech_r2/westech_r2/templates/print_format"

PRINT_FORMATS = [
    {
        "name": "Green Sheet",
        "doc_type": "Pallet",
        "file": "green-sheet.html",
        "description": "R2 Data-Bearing Equipment Intake Sheet",
    },
    {
        "name": "Purple Sheet",
        "doc_type": "Load",
        "file": "purple-sheet.html",
        "description": "Load Tracking Worksheet",
    },
    {
        "name": "Pallet Label 4x6",
        "doc_type": "Pallet",
        "file": "pallet-label-4x6.html",
        "description": "4x6 Pallet Shipping Label",
    },
    {
        "name": "R2 Special Handling Log",
        "doc_type": "Pallet",
        "file": "r2-special-handling-log.html",
        "description": "R2 Special Handling Chain of Custody Log",
    },
    {
        "name": "R2 UW Label",
        "doc_type": "Pallet",
        "file": "r2-uw-label.html",
        "description": "R2 Unwanted/Unknown Material Label",
    },
    {
        "name": "Special Handling Log",
        "doc_type": "Load",
        "file": "special-handling-log.html",
        "description": "Special Handling Chain of Custody Log",
    },
]

def import_print_formats():
    frappe.init(site="erpnext.local")
    frappe.connect()
    
    for pf in PRINT_FORMATS:
        file_path = os.path.join(TEMPLATE_DIR, pf["file"])
        
        if not os.path.exists(file_path):
            print(f"⚠️  File not found: {file_path}")
            continue
        
        with open(file_path, "r") as f:
            html_content = f.read()
        
        # Check if Print Format already exists
        existing = frappe.get_doc("Print Format", pf["name"]) if frappe.db.exists("Print Format", pf["name"]) else None
        
        if existing:
            # Update existing
            existing.html = html_content
            existing.description = pf["description"]
            existing.save()
            print(f"✓ Updated: {pf['name']}")
        else:
            # Create new
            new_pf = frappe.get_doc({
                "doctype": "Print Format",
                "name": pf["name"],
                "print_format_name": pf["name"],
                "doc_type": pf["doc_type"],
                "html": html_content,
                "description": pf["description"],
                "standard": "No",
                "custom_format": 1,
            })
            new_pf.insert()
            print(f"✓ Created: {pf['name']}")
    
    frappe.db.commit()
    print("\n✓ All print formats imported successfully")
    
    frappe.destroy()

if __name__ == "__main__":
    import_print_formats()
