import frappe


def execute():
    """Add new Employee columns directly with reduced varchar lengths to fit within
    MySQL's 65535-byte row size limit. tabEmployee is near the limit, so we use
    length=50 for citizenship_country and length=20 for residence_permit_fin
    instead of the default varchar(140)."""

    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` varchar(50) NULL DEFAULT NULL")
    if "residence_permit_fin" not in existing_columns:
        to_add.append("ADD COLUMN `residence_permit_fin` varchar(20) NULL DEFAULT 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 in tabEmployee, skipping.")

    # Ensure Custom Field records also use the reduced lengths so Frappe does not
    # try to ALTER the columns back to varchar(140) on the next migrate.
    for fieldname, length in [("citizenship_country", 50), ("residence_permit_fin", 20)]:
        cf_name = frappe.db.get_value(
            "Custom Field", {"dt": "Employee", "fieldname": fieldname}, "name"
        )
        if cf_name:
            frappe.db.sql(
                "UPDATE `tabCustom Field` SET `length`=%s WHERE `name`=%s",
                (length, cf_name),
            )
            frappe.db.commit()
