import frappe
import os

frappe.init(site="erpnext.local")
frappe.connect()

labels_dir = "/tmp/labels"
labels = [
    {"name": "R2 UW Label GA FL AZ", "doctype": "Pallet", "file": "8.1.1-F R2 UW Label GA FL AZ v2.0 - draft.pdf"},
    {"name": "Resale Label", "doctype": "Pallet", "file": "8.1.1-F Resale Label Issue 10.0.pdf"},
    {"name": "Arizona Processing Label", "doctype": "Pallet", "file": "8.1.1-F Arizona Processing Label 1.0.pdf"},
    {"name": "Unrestricted Streams", "doctype": "Pallet", "file": "4.4.6.3-F Unrestricted Streams Issue 2.0.pdf"},
    {"name": "Unacceptable Items", "doctype": "Pallet", "file": "8.1.1-F Unacceptible Items 1.0 Fill.pdf"},
]

for label in labels:
    try:
        # Check if Print Format already exists
        existing = frappe.db.exists("Print Format", label["name"])
        if existing:
            print(f"✓ Print Format '{label['name']}' already exists")
            continue
        
        # Read PDF file
        pdf_path = os.path.join(labels_dir, label["file"])
        if not os.path.exists(pdf_path):
            print(f"✗ File not found: {pdf_path}")
            continue
        
        with open(pdf_path, "rb") as f:
            pdf_content = f.read()
        
        # Create Print Format
        pf = frappe.get_doc({
            "doctype": "Print Format",
            "name": label["name"],
            "standard": "No",
            "custom_format": 1,
            "print_format_type": "PDF",
            "doc_type": label["doctype"],
            "resource": pdf_content,
            "default_print_language": "en",
        })
        pf.insert()
        frappe.db.commit()
        print(f"✓ Created Print Format: {label['name']}")
        
    except Exception as e:
        print(f"✗ Error importing {label['name']}: {e}")
        frappe.db.rollback()

frappe.destroy()
print("\nDone! Labels imported as Print Formats.")
