import frappe


def execute():
    """tabEmployee is at MySQL's 65535-byte row size limit.
    TEXT columns are excluded from this limit (MySQL explicitly states 'not counting BLOBs').
    This patch adds our new Employee columns as TEXT and updates the Custom Field records
    to fieldtype='Small Text' so Frappe's schema sync agrees with the actual column types."""

    # Step 1: update Custom Field records so schema sync uses TEXT, not varchar
    text_fields = ("citizenship_country", "residence_permit_fin")
    for fieldname in text_fields:
        cf_name = frappe.db.get_value(
            "Custom Field", {"dt": "Employee", "fieldname": fieldname}, "name"
        )
        if cf_name:
            frappe.db.sql(
                "UPDATE `tabCustom Field` SET fieldtype='Small Text', options='', length=0 WHERE name=%s",
                (cf_name,),
            )

    frappe.db.commit()

    # Step 2: add missing columns directly as TEXT (excluded from 65535 limit)
    existing_columns = {row[0] for row in frappe.db.sql("SHOW COLUMNS FROM `tabEmployee`")}

    to_add = []
    if "citizenship_country" not in existing_columns:
        to_add.append("ADD COLUMN `citizenship_country` text NULL")
    if "residence_permit_fin" not in existing_columns:
        to_add.append("ADD COLUMN `residence_permit_fin` text NULL")
    if "residence_permit_not_available" not in existing_columns:
        to_add.append("ADD COLUMN `residence_permit_not_available` tinyint(4) NOT NULL DEFAULT 0")

    if to_add:
        frappe.db.sql("ALTER TABLE `tabEmployee` " + ", ".join(to_add))
        frappe.db.commit()
        print(f"Added columns to tabEmployee: {[s.split('`')[1] for s in to_add]}")
    else:
        print("Columns already exist, skipping ALTER TABLE.")
