# -*- coding: utf-8 -*-
"""
F0NT Autotune - Dedicated Thai Anchor Mark & OpenType Plugin for FontLab 7 & FontLab 8
Bilingual (TH/EN)
"""

import html

import fontlab as fl6
from PythonQt import QtCore, QtGui

__version__ = "1.1"

# ---- การตั้งค่า ----
WINDOW_OBJECT_NAME = "F0NTAutotunePanel"
# marker ใน feature ที่สคริปต์สร้าง (ใช้แยก feature ของ F0NT ออกจาก feature ที่ผู้ใช้เขียนเอง)
FEA_MARKER = "F0NT Autotune"
# marker ครอบบล็อก table GDEF ใน Features prefix
GDEF_PREFIX_BEGIN = "# >>> F0NT Autotune GDEF (auto-generated)"
GDEF_PREFIX_END = "# <<< F0NT Autotune GDEF"

TOP_VOWEL_UNICODES = (0x0E31, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E4D)
BOTTOM_VOWEL_UNICODES = (0x0E38, 0x0E39, 0x0E3A)
ASCENDER_TAIL_UNICODES = (0x0E1B, 0x0E1D, 0x0E1F, 0x0E2C)
DESCENDER_CUT_UNICODES = (0x0E0D, 0x0E10, 0x0E0E, 0x0E0F)
DEEP_STEM_UNICODES = (0x0E0E, 0x0E0F, 0x0E24, 0x0E26)
# ค่า flGlyph.otGlyphClass (ยืนยันใน FontLab 8.4.2)
OT_CLASS_NONE, OT_CLASS_BASE, OT_CLASS_LIGATURE, OT_CLASS_MARK = 0, 1, 2, 3
OT_CLASS_NAMES = {0: 'None', 1: 'Base', 2: 'Ligature', 3: 'Mark'}
# ตัวอักษรที่ใช้ดึงค่า "ความสูงพยัญชนะไทย" (ขอบบนของ outline ใน master ปัจจุบัน)
THAI_HEIGHT_SOURCES = (('ก', 0x0E01), ('ด', 0x0E14), ('บ', 0x0E1A), ('อ', 0x0E2D))

# อีโมจิใน log -> สัญลักษณ์เรียบๆ บนแถบสถานะ
STATUS_SYMBOLS = (('🎉', '✓'), ('✅', '✓'), ('🗑️', '✓'), ('🏷️', '✓'), ('⚠️', '⚠'), ('❌', '✕'))


def _get(obj, attr):
    """อ่านค่าจาก object ของ FontLab ที่อาจเป็น property หรือ method ก็ได้"""
    val = getattr(obj, attr)
    return val() if callable(val) else val


def _get_name(obj):
    try:
        return str(_get(obj, 'name'))
    except Exception:
        return "?"

# ตารางเทียบชื่อ Glyph มาตรฐาน -> Unicode
THAI_NAME_TO_UNICODE = {
    'kokai': 0x0E01, 'khokhai': 0x0E02, 'khokhuat': 0x0E03, 'khokhwai': 0x0E04,
    'khokhon': 0x0E05, 'khorakhang': 0x0E06, 'ngongu': 0x0E07, 'chochan': 0x0E08,
    'choching': 0x0E09, 'chochang': 0x0E0A, 'soso': 0x0E0B, 'chochoe': 0x0E0C,
    'yoying': 0x0E0D, 'dochada': 0x0E0E, 'topatak': 0x0E0F, 'thothan': 0x0E10,
    'thonangmontho': 0x0E11, 'thophuthao': 0x0E12, 'nonen': 0x0E13, 'dodek': 0x0E14,
    'totao': 0x0E15, 'thothung': 0x0E16, 'thothahan': 0x0E17, 'thothong': 0x0E18,
    'nonu': 0x0E19, 'bobaimai': 0x0E1A, 'popla': 0x0E1B, 'phophung': 0x0E1C,
    'fofa': 0x0E1D, 'phophan': 0x0E1E, 'fofan': 0x0E1F, 'phosamphao': 0x0E20,
    'moma': 0x0E21, 'yoyak': 0x0E22, 'rorua': 0x0E23, 'ru': 0x0E24,
    'loling': 0x0E25, 'lu': 0x0E26, 'wowaen': 0x0E27, 'sosala': 0x0E28,
    'sorusi': 0x0E29, 'sosua': 0x0E2A, 'hohip': 0x0E2B, 'lochula': 0x0E2C,
    'oang': 0x0E2D, 'honokhuk': 0x0E2E, 'paiyannoi': 0x0E2F, 'saraa': 0x0E30,
    'maihanakat': 0x0E31, 'saraaa': 0x0E32, 'saraam': 0x0E33,
    'sarai': 0x0E34, 'saraii': 0x0E35, 'saraue': 0x0E36, 'sarauee': 0x0E37,
    'sarau': 0x0E38, 'sarauu': 0x0E39, 'phinthu': 0x0E3A, 'sarae': 0x0E40,
    'saraae': 0x0E41, 'sarao': 0x0E42, 'saraaimaimalai': 0x0E43, 'saraaimaimuan': 0x0E44,
    'lakkhangyao': 0x0E45, 'maiyamok': 0x0E46, 'maitaikhu': 0x0E47,
    'maiek': 0x0E48, 'maitho': 0x0E49, 'maitri': 0x0E4A, 'maichattawa': 0x0E4B,
    'thanthakhat': 0x0E4C, 'nikhahit': 0x0E4D, 'nikkhahit': 0x0E4D, 'yamakkan': 0x0E4E,
    'fongman': 0x0E4F, 'zerothai': 0x0E50, 'onethai': 0x0E51, 'twothai': 0x0E52,
    'threethai': 0x0E53, 'fourthai': 0x0E54, 'fivethai': 0x0E55, 'sixthai': 0x0E56,
    'seventhai': 0x0E57, 'eightthai': 0x0E58, 'ninethai': 0x0E59,

    # Adobe Glyph List (AGLFN) & FontLab standard Thai aliases:
    'u-thai': 0x0E38, 'uu-thai': 0x0E39, 'phinthu-thai': 0x0E3A,
    'i-thai': 0x0E34, 'ii-thai': 0x0E35, 'ue-thai': 0x0E36, 'uee-thai': 0x0E37,
    'maihanakat-thai': 0x0E31, 'nikhahit-thai': 0x0E4D, 'nikkhahit-thai': 0x0E4D,
    'maiek-thai': 0x0E48, 'maitho-thai': 0x0E49, 'maitri-thai': 0x0E4A,
    'maichattawa-thai': 0x0E4B, 'thanthakhat-thai': 0x0E4C,
    'maitaikhu-thai': 0x0E47, 'yamakkan-thai': 0x0E4E,
    'saraa-thai': 0x0E30, 'saraaa-thai': 0x0E32, 'saraam-thai': 0x0E33,
    'sarae-thai': 0x0E40, 'saraae-thai': 0x0E41, 'sarao-thai': 0x0E42,
    'saraaimaimalai-thai': 0x0E43, 'saraaimaimuan-thai': 0x0E44,

    # Underscore & Hyphen aliases (e.g. sara_u, sara-u, sara_uu):
    'sara_u': 0x0E38, 'sara-u': 0x0E38, 'sarau': 0x0E38,
    'sara_uu': 0x0E39, 'sara-uu': 0x0E39, 'sarauu': 0x0E39,
    'sara_i': 0x0E34, 'sara-i': 0x0E34,
    'sara_ii': 0x0E35, 'sara-ii': 0x0E35,
    'sara_ue': 0x0E36, 'sara-ue': 0x0E36,
    'sara_uee': 0x0E37, 'sara-uee': 0x0E37,
    'sara_a': 0x0E30, 'sara-a': 0x0E30,
    'sara_aa': 0x0E32, 'sara-aa': 0x0E32,
    'sara_am': 0x0E33, 'sara-am': 0x0E33,
    'mai_ek': 0x0E48, 'mai-ek': 0x0E48,
    'mai_tho': 0x0E49, 'mai-tho': 0x0E49,
    'mai_tri': 0x0E4A, 'mai-tri': 0x0E4A,
    'mai_chattawa': 0x0E4B, 'mai-chattawa': 0x0E4B,
    'mai_hanakat': 0x0E31, 'mai-hanakat': 0x0E31,
    'mai_taikhu': 0x0E47, 'mai-taikhu': 0x0E47
}

# Suffix ที่นิยมใช้สำหรับตัวพิเศษภาษาไทย
DESCENDER_LESS_SUFFIXES = ('.less', '.short', '.no', '.sub', '.alt', '.descless', '.low')
SHIFTED_LEFT_SUFFIXES = ('.left', '.narrow', '.lowleft', '.small', '.alt', '.short')
UPSTAIRS_SUFFIXES = ('.up', '.high', '.top', '.small')

# AFDKO Reserved Words (cannot be used bare as glyph names in OpenType feature files)
AFDKO_RESERVED_WORDS = {
    'NULL', 'anchor', 'table', 'feature', 'lookup', 'languagesystem', 'script', 'language',
    'subtable', 'lookupflag', 'substitute', 'sub', 'by', 'from', 'position', 'pos', 'enum',
    'enumerate', 'markClass', 'mark', 'base', 'ligature', 'component', 'cursive', 'device',
    'parameters', 'valueRecordDef', 'anchorDef', 'glyphclass', 'GlyphClassDef', 'Attach',
    'LigatureCaretByPos', 'LigatureCaretByIndex', 'include', 'anon', 'anonymous', 'nameid',
    'RightToLeft', 'IgnoreBaseGlyphs', 'IgnoreLigatures', 'IgnoreMarks', 'MarkAttachmentType',
    'UseMarkFilteringSet'
}

UI_TEXT = {
    'th': {
        'app_title': 'F0NT Autotune',
        'tip_help': 'คู่มือการใช้งาน',
        'tip_tools': 'เครื่องมือ',

        'lbl_scope': 'ขอบเขต',
        'scope_font': 'ทั้งฟอนต์',
        'scope_sel': 'Glyph ที่เปิดอยู่',
        'chk_all_masters': 'ทำทุก Master',
        'lbl_mode': 'รูปแบบ',
        'rb_std': 'พื้นฐาน',
        'rb_adv': 'ละเอียด',
        'tip_mode': 'พื้นฐาน: ใช้ anchor top / bottom ชุดเดียว\nละเอียด: แยก anchor ตามวรรณยุกต์แต่ละตัว และปรับระยะเยื้องได้',
        'btn_open_adv': 'ปรับระยะเยื้อง…',
        'lbl_thai_height': 'ความสูงพยัญชนะ',
        'tip_thai_height': 'ความสูงของพยัญชนะไทย ใช้วาง anchor บน (top) — ดึงจากขอบบนของตัวอักษรที่เลือก หรือพิมพ์เอง',
        'tip_fetch_height': 'ดึงค่าจากตัวอักษรที่เลือก',

        'more_options': 'ตัวเลือกเพิ่มเติม',
        'chk_zero': 'ตั้งความกว้างสระลอยและวรรณยุกต์เป็น 0',
        'chk_ow_anc': 'เขียนทับ anchor ชื่อเดียวกันที่มีอยู่',
        'chk_clr_anc': 'ลบ anchor เดิมทั้งหมดใน glyph ไทยก่อนปัก',
        'chk_clean_old_fea': 'อนุญาตให้เขียนทับ ccmp / mark / mkmk เดิม (ถามก่อน)',
        'chk_gdef_class': 'เขียน table GDEF ลง Features prefix (ปกติไม่จำเป็น)',

        'btn_run_main': 'ปักหมุด Anchor',
        'btn_run_main_sel': 'ปักหมุด Anchor — Glyph ที่เปิดอยู่',
        'btn_assign_gdef_now': 'ตรวจ OT Class ไทย',
        'btn_clear_anc_now': 'ล้าง Anchor ไทย…',

        'ready_status': 'พร้อมทำงาน',
        'next_step_init': 'ทดสอบกับไฟล์สำเนาก่อนเสมอ — สคริปต์ไม่มี Undo',
        'next_step_done': 'เสร็จแล้ว — เปิด Window › Panels › Features กด Compile แล้วดูผลใน Preview',
        'btn_stop': 'หยุด',
        'log_toggle': 'รายละเอียด',
        'btn_clear_log': 'ล้าง',

        'menu_diag': 'ตรวจระบบ (Diagnostics)',
        'menu_scan': 'นับตัวอักษรไทยในฟอนต์',
        'menu_copy_words': 'คัดลอกคำทดสอบ',
        'menu_debug': 'Log แบบละเอียด',

        'adv_win_title': 'ระยะเยื้อง Anchor',
        'adv_hint': 'ค่าบวก = เลื่อนขวา / ขึ้น · ค่าลบ = เลื่อนซ้าย / ลง · หน่วยที่ 1000 UPM (ปรับตาม UPM ให้อัตโนมัติ)',
        'adv_sec_tones': 'วรรณยุกต์และเครื่องหมายบน',
        'adv_sec_upper': 'สระบนและนิคหิต',
        'adv_sec_lower': 'สระล่างและพินทุ',
        'adv_sec_tail': 'หลบหาง ป ฝ ฟ ฬ',
        'adv_reset_all': 'คืนค่าเริ่มต้นทั้งหมด',
        'adv_reset_one': 'คืนค่าเริ่มต้น ({})',

        'help_main_title': 'คู่มือ F0NT Autotune',
        'help_main_body': (
            '<b>ปักหมุด Anchor ภาษาไทยและสร้าง Features (ccmp / mark / mkmk)</b><br><br>'
            '<b>ขั้นตอน</b><br>'
            '1. เลือก <b>ขอบเขต</b>: ทั้งฟอนต์ หรือเฉพาะ Glyph ที่เปิดอยู่ (ไว้ทดลองทีละตัว — โหมดนี้ไม่เขียน Features)<br>'
            '2. ตรวจ <b>ความสูงพยัญชนะ</b> (ดึงจาก ก / ด / บ / อ ให้อัตโนมัติ) ให้ตรงกับขอบบนของพยัญชนะ<br>'
            '3. เลือก <b>รูปแบบ</b>: พื้นฐาน หรือ ละเอียด (กด “ปรับระยะเยื้อง…” เพื่อเลื่อนวรรณยุกต์ / สระรายตัว)<br>'
            '4. กด <b>ปักหมุด Anchor</b> แล้วยืนยัน<br>'
            '5. เปิด Window › Panels › Features กด Compile แล้วทดสอบคำใน Preview (เมนู ⋯ › คัดลอกคำทดสอบ)<br><br>'
            '<b>ควรรู้</b><br>'
            '• สคริปต์ไม่มี Undo — ทดสอบกับไฟล์สำเนาเสมอ<br>'
            '• Feature ccmp / mark / mkmk ที่ไม่ได้สร้างโดย F0NT จะไม่ถูกเขียนทับ (เว้นแต่เปิดใน “ตัวเลือกเพิ่มเติม”)<br>'
            '• ถ้ามีข้อผิดพลาด กด “รายละเอียด” ที่ด้านล่างเพื่อดู log<br><br>'
            'คู่มือฉบับเต็ม: <code>docs/manual.md</code>'
        )
    },
    'en': {
        'app_title': 'F0NT Autotune',
        'tip_help': 'User guide',
        'tip_tools': 'Tools',

        'lbl_scope': 'Scope',
        'scope_font': 'Whole font',
        'scope_sel': 'Active glyph',
        'chk_all_masters': 'All masters',
        'lbl_mode': 'Mode',
        'rb_std': 'Standard',
        'rb_adv': 'Detailed',
        'tip_mode': 'Standard: one top / bottom anchor set\nDetailed: per-tone anchors with adjustable offsets',
        'btn_open_adv': 'Offsets…',
        'lbl_thai_height': 'Consonant height',
        'tip_thai_height': 'Thai consonant height used for top anchors — read from the top of the selected glyph, or type a value',
        'tip_fetch_height': 'Read from the selected glyph',

        'more_options': 'More options',
        'chk_zero': 'Set floating vowels & tone marks to zero width',
        'chk_ow_anc': 'Overwrite existing anchors with the same name',
        'chk_clr_anc': 'Remove all existing anchors on Thai glyphs first',
        'chk_clean_old_fea': 'Allow overwriting existing ccmp / mark / mkmk (asks first)',
        'chk_gdef_class': 'Write table GDEF into Features prefix (usually unneeded)',

        'btn_run_main': 'Place Anchors',
        'btn_run_main_sel': 'Place Anchors — Active Glyph',
        'btn_assign_gdef_now': 'Check Thai OT Classes',
        'btn_clear_anc_now': 'Clear Thai Anchors…',

        'ready_status': 'Ready',
        'next_step_init': 'Always test on a copy first — the script has no undo',
        'next_step_done': 'Done — open Window › Panels › Features, click Compile, then check the Preview',
        'btn_stop': 'Stop',
        'log_toggle': 'Details',
        'btn_clear_log': 'Clear',

        'menu_diag': 'Diagnostics',
        'menu_scan': 'Count Thai glyphs in font',
        'menu_copy_words': 'Copy test words',
        'menu_debug': 'Verbose log',

        'adv_win_title': 'Anchor Offsets',
        'adv_hint': 'Positive = right / up · Negative = left / down · Units at 1000 UPM (scaled automatically)',
        'adv_sec_tones': 'Tone marks & upper signs',
        'adv_sec_upper': 'Upper vowels & nikhahit',
        'adv_sec_lower': 'Lower vowels & phinthu',
        'adv_sec_tail': 'Tall-tail dodging (ป ฝ ฟ ฬ)',
        'adv_reset_all': 'Reset all',
        'adv_reset_one': 'Reset to default ({})',

        'help_main_title': 'F0NT Autotune Guide',
        'help_main_body': (
            '<b>Thai anchor placement and Features (ccmp / mark / mkmk)</b><br><br>'
            '<b>Steps</b><br>'
            '1. Choose a <b>Scope</b>: whole font, or the active glyph (for trying one glyph — Features are not written)<br>'
            '2. Check the <b>Consonant height</b> (read automatically from ก / ด / บ / อ)<br>'
            '3. Choose a <b>Mode</b>: Standard or Detailed (use “Offsets…” to shift individual marks)<br>'
            '4. Click <b>Place Anchors</b> and confirm<br>'
            '5. Open Window › Panels › Features, click Compile, and test in the Preview (⋯ › Copy test words)<br><br>'
            '<b>Good to know</b><br>'
            '• No undo — always test on a copy<br>'
            '• ccmp / mark / mkmk not created by F0NT are never overwritten unless allowed in “More options”<br>'
            '• If something fails, open “Details” at the bottom to see the log<br><br>'
            'Full manual: <code>docs/manual.md</code>'
        )
    }
}

# ช่องปรับระยะเยื้อง: (ชื่อ attribute, ป้ายไทย, ป้ายอังกฤษ, ต่ำสุด, สูงสุด, ค่าเริ่มต้น)
ADV_SECTIONS = (
    ('adv_sec_tones', (
        ('spin_ek', 'ไม้เอก  ่', 'Mai Ek  ่', -300, 300, 0),
        ('spin_tho', 'ไม้โท  ้', 'Mai Tho  ้', -300, 300, -25),
        ('spin_tri', 'ไม้ตรี  ๊', 'Mai Tri  ๊', -300, 300, 0),
        ('spin_chattawa', 'ไม้จัตวา  ๋', 'Mai Chattawa  ๋', -300, 300, 0),
        ('spin_thanthakhat', 'การันต์  ์', 'Thanthakhat  ์', -300, 300, -40),
        ('spin_maitaikhu', 'ไม้ไต่คู้  ็', 'Mai Taikhu  ็', -300, 300, 0),
        ('spin_yamakkan', 'ยามักการ  ๎', 'Yamakkan  ๎', -300, 300, 0),
    )),
    ('adv_sec_upper', (
        ('spin_maihanakat', 'ไม้หันอากาศ  ั', 'Mai Han-akat  ั', -300, 300, 0),
        ('spin_sarai', 'สระอิ  ิ', 'Sara I  ิ', -300, 300, 0),
        ('spin_saraii', 'สระอี  ี', 'Sara Ii  ี', -300, 300, 0),
        ('spin_saraue', 'สระอึ  ึ', 'Sara Ue  ึ', -300, 300, 0),
        ('spin_sarauee', 'สระอือ  ื', 'Sara Uee  ื', -300, 300, 0),
        ('spin_nikhahit', 'นิคหิต  ํ', 'Nikhahit  ํ', -300, 300, 0),
        ('spin_upper_y', 'ความสูงสระบน (Y)', 'Upper vowel height (Y)', -200, 200, 0),
    )),
    ('adv_sec_lower', (
        ('spin_sarau', 'สระอุ  ุ', 'Sara U  ุ', -300, 300, 0),
        ('spin_sarauu', 'สระอู  ู', 'Sara Uu  ู', -300, 300, 0),
        ('spin_phinthu', 'พินทุ  ฺ', 'Phinthu  ฺ', -300, 300, 0),
        ('spin_lower_y', 'ความสูงสระล่าง (Y)', 'Lower vowel height (Y)', -200, 200, 0),
    )),
    ('adv_sec_tail', (
        ('spin_tail_shift', 'เลื่อน anchor บน', 'Top anchor shift', -350, 100, -75),
    )),
)

TEST_WORDS = (
    "ปี่ ปี้ ปิ๊ ปิ๋ ปิ์ ป็ ป๎\n"
    "ฟี่ ฟี้ ฟิ๊ ฟิ๋ ฟิ์ ฟ็ ฟ๎\n"
    "ฝี่ ฝี้ ฝิ๊ ฝิ๋ ฝิ์ ฝ็ ฝ๎\n"
    "ฬี่ ฬี้ ฬิ๊ ฬิ๋ ฬิ์ ฬ็ ฬ๎\n"
    "กั่ กั้ กั๊ กั๋ กิ์ ก่ำ ก้ำ น้ำ\n"
    "ญุ ญู ฐุ ฐู ฎุ ฎู ฏุ ฏู\n"
    "ก็ เป็ เล็ก วัน จัด กัก อนึ่ง"
)


def _ensure_ui_indicator_icons():
    import os
    import zlib
    import struct
    import tempfile

    def write_rgba_png(path, width, height, pixel_fn):
        raw_rows = []
        for y in range(height):
            row = bytearray([0])
            for x in range(width):
                r, g, b, a = pixel_fn(x, y)
                row.extend((r, g, b, a))
            raw_rows.append(bytes(row))
        raw_data = b"".join(raw_rows)
        compressed = zlib.compress(raw_data, 9)

        def make_chunk(chunk_type, data):
            chunk = chunk_type + data
            crc = zlib.crc32(chunk) & 0xffffffff
            return struct.pack(">I", len(data)) + chunk + struct.pack(">I", crc)

        png = (
            b"\x89PNG\r\n\x1a\n" +
            make_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) +
            make_chunk(b"IDAT", compressed) +
            make_chunk(b"IEND", b"")
        )
        with open(path, "wb") as f:
            f.write(png)

    cache_dir = os.path.join(tempfile.gettempdir(), "f0nt_autotune_assets")
    try:
        os.makedirs(cache_dir)
    except Exception:
        pass

    chk_path = os.path.join(cache_dir, "chk_on.png")
    rad_path = os.path.join(cache_dir, "rad_on.png")

    if not os.path.exists(chk_path):
        def chk_px(x, y):
            pts = [(3, 8), (4, 9), (5, 10), (6, 11), (7, 10), (8, 9), (9, 8), (10, 7), (11, 6), (12, 5)]
            pts_thick = [(x, y - 1) for x, y in pts] + [(x, y + 1) for x, y in pts]
            if (x, y) in pts or (x, y) in pts_thick:
                return 255, 255, 255, 255
            return 0, 0, 0, 0
        try:
            write_rgba_png(chk_path, 16, 16, chk_px)
        except Exception:
            pass

    if not os.path.exists(rad_path):
        def rad_px(x, y):
            dx = x - 7.5
            dy = y - 7.5
            d = (dx * dx + dy * dy) ** 0.5
            if d <= 3.6:
                return 255, 255, 255, 255
            return 0, 0, 0, 0
        try:
            write_rgba_png(rad_path, 16, 16, rad_px)
        except Exception:
            pass

    return chk_path.replace("\\", "/"), rad_path.replace("\\", "/")


_CHK_ICON_PATH, _RAD_ICON_PATH = _ensure_ui_indicator_icons()

# ---- ธีม (ตามธีมสว่าง / มืดของ FontLab อัตโนมัติ) ----
THEME_COLORS = {
    'dark': {
        'bg': '#232427', 'surface': '#2d2e32', 'surface_hover': '#36373c', 'field': '#1b1c1f',
        'border': '#3c3d42', 'border_strong': '#5a5b61', 'text': '#ececee', 'muted': '#9b9ca3',
        'accent': '#2e9d68', 'accent_hover': '#35b376', 'accent_text': '#ffffff', 'accent_soft': '#203a2d',
        'danger': '#e5675f'
    },
    'light': {
        'bg': '#f4f4f6', 'surface': '#ffffff', 'surface_hover': '#ececf0', 'field': '#ffffff',
        'border': '#d6d6dc', 'border_strong': '#b4b4bc', 'text': '#1d1d1f', 'muted': '#6e6e76',
        'accent': '#1f8a57', 'accent_hover': '#24a065', 'accent_text': '#ffffff', 'accent_soft': '#e2f3e9',
        'danger': '#c8443c'
    }
}

STYLESHEET_TEMPLATE = """
QDialog {{ background: {bg}; color: {text}; font-size: 12px; }}
QLabel {{ color: {text}; background: transparent; }}
QLabel#title {{ font-size: 15px; font-weight: 600; }}
QLabel#formLabel {{ color: {muted}; }}
QLabel#section {{ color: {muted}; font-size: 11px; font-weight: 600; padding-top: 4px; }}
QLabel#hint {{ color: {muted}; font-size: 11px; }}
QLabel#status {{ color: {text}; font-size: 11px; }}

QPushButton {{ background: {surface}; color: {text}; border: 1px solid {border};
    border-radius: 6px; padding: 4px 10px; }}
QPushButton:hover {{ background: {surface_hover}; }}
QPushButton:disabled {{ color: {muted}; }}
QPushButton::menu-indicator {{ image: none; width: 0px; }}

QPushButton#primary {{ background: {accent}; color: {accent_text}; border: none; border-radius: 8px;
    font-size: 13px; font-weight: 600; padding: 9px 12px; }}
QPushButton#primary:hover {{ background: {accent_hover}; }}
QPushButton#primary:disabled {{ background: {border}; color: {muted}; }}

QPushButton#segFirst, QPushButton#segMid, QPushButton#segLast {{ border-radius: 0px; padding: 4px 12px; }}
QPushButton#segFirst {{ border-top-left-radius: 6px; border-bottom-left-radius: 6px; }}
QPushButton#segMid, QPushButton#segLast {{ border-left: none; }}
QPushButton#segLast {{ border-top-right-radius: 6px; border-bottom-right-radius: 6px; }}
QPushButton#segFirst:checked, QPushButton#segMid:checked, QPushButton#segLast:checked {{
    background: {accent}; color: {accent_text}; border-color: {accent}; }}

QPushButton#chip {{ border-radius: 11px; padding: 3px 12px; }}
QPushButton#chip:checked {{ background: {accent_soft}; border-color: {accent}; }}

QPushButton#link, QPushButton#dangerLink {{ background: transparent; border: none; padding: 2px 0px; color: {accent}; }}
QPushButton#dangerLink {{ color: {danger}; }}
QPushButton#link:hover, QPushButton#dangerLink:hover {{ text-decoration: underline; }}
QPushButton#link:disabled {{ color: {muted}; }}

QPushButton#icon {{ border-radius: 11px; min-width: 22px; max-width: 22px; min-height: 22px; max-height: 22px;
    padding: 0px; font-weight: 600; }}
QPushButton#reset {{ background: transparent; border: none; color: {muted}; padding: 0px 2px; }}
QPushButton#reset:hover {{ color: {accent}; }}

QToolButton#disclosure {{ background: transparent; border: none; color: {muted}; font-weight: 600; padding: 2px 0px; }}
QToolButton#disclosure:hover {{ color: {text}; }}

QCheckBox {{ spacing: 7px; color: {text}; }}
QCheckBox:disabled {{ color: {muted}; }}
QCheckBox::indicator {{ width: 14px; height: 14px; border: 1px solid {border_strong}; border-radius: 4px; background: {field}; }}
QCheckBox::indicator:checked {{ background: {accent}; border-color: {accent}; image: url("{chk_icon}"); }}

QLineEdit, QSpinBox, QComboBox {{ background: {field}; color: {text}; border: 1px solid {border};
    border-radius: 5px; padding: 2px 6px; min-height: 20px; }}
QLineEdit:focus, QSpinBox:focus, QComboBox:focus {{ border-color: {accent}; }}
QComboBox QAbstractItemView {{ background: {surface}; color: {text}; selection-background-color: {accent}; }}

QFrame#divider {{ background: {border}; border: none; min-height: 1px; max-height: 1px; }}
QProgressBar {{ background: {surface}; border: none; border-radius: 2px; min-height: 4px; max-height: 4px; }}
QProgressBar::chunk {{ background: {accent}; border-radius: 2px; }}
QTextEdit {{ background: {field}; color: {text}; border: 1px solid {border}; border-radius: 6px;
    font-family: Menlo, monospace; font-size: 11px; padding: 4px; }}
QSlider::groove:horizontal {{ height: 4px; background: {border}; border-radius: 2px; }}
QSlider::sub-page:horizontal {{ background: {accent}; border-radius: 2px; }}
QSlider::handle:horizontal {{ width: 14px; height: 14px; margin: -5px 0px; border-radius: 7px; background: {accent}; }}
QMenu {{ background: {surface}; color: {text}; border: 1px solid {border}; padding: 4px; }}
QMenu::item {{ padding: 5px 18px 5px 22px; border-radius: 4px; }}
QMenu::item:selected {{ background: {accent}; color: {accent_text}; }}
QMenu::separator {{ height: 1px; background: {border}; margin: 4px 6px; }}
QMessageBox QLabel {{ min-width: 360px; }}
"""


def build_stylesheet():
    """stylesheet ตามธีมปัจจุบันของ FontLab (ตรวจจากความสว่างของสีพื้นหลังหน้าต่าง)"""
    try:
        is_dark = QtGui.QApplication.palette().color(QtGui.QPalette.Window).lightness() < 128
    except Exception:
        is_dark = True
    colors = dict(THEME_COLORS['dark' if is_dark else 'light'])
    colors['chk_icon'] = _CHK_ICON_PATH
    return STYLESHEET_TEMPLATE.format(**colors)


def make_segmented(owner, count):
    """ปุ่มแบบแบ่งส่วน (เลือกได้ทีละปุ่ม) คืน (widget, [ปุ่ม])"""
    box = QtGui.QWidget()
    lay = QtGui.QHBoxLayout(box)
    lay.setContentsMargins(0, 0, 0, 0)
    lay.setSpacing(0)
    group = QtGui.QButtonGroup(box)
    group.setExclusive(True)
    owner._button_groups.append(group)  # เก็บ reference กัน garbage collector
    buttons = []
    for i in range(count):
        btn = QtGui.QPushButton("")
        btn.setCheckable(True)
        btn.setCursor(QtCore.Qt.PointingHandCursor)
        btn.setObjectName('segFirst' if i == 0 else ('segLast' if i == count - 1 else 'segMid'))
        group.addButton(btn)
        lay.addWidget(btn)
        buttons.append(btn)
    lay.addStretch()
    return box, buttons


def make_disclosure(window, content):
    """ปุ่มลูกศรสำหรับพับ / กาง content (เริ่มต้นพับไว้)"""
    btn = QtGui.QToolButton()
    btn.setObjectName('disclosure')
    btn.setCheckable(True)
    btn.setCursor(QtCore.Qt.PointingHandCursor)
    btn.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
    btn.setArrowType(QtCore.Qt.RightArrow)
    content.setVisible(False)

    def on_toggle(opened):
        content.setVisible(opened)
        btn.setArrowType(QtCore.Qt.DownArrow if opened else QtCore.Qt.RightArrow)
        window.adjustSize()
    btn.toggled.connect(on_toggle)
    return btn


def make_button(object_name, slot=None):
    btn = QtGui.QPushButton("")
    btn.setObjectName(object_name)
    btn.setCursor(QtCore.Qt.PointingHandCursor)
    if slot is not None:
        btn.clicked.connect(slot)
    return btn


def make_label(object_name, word_wrap=False):
    lbl = QtGui.QLabel("")
    lbl.setObjectName(object_name)
    lbl.setWordWrap(word_wrap)
    return lbl


def make_divider():
    line = QtGui.QFrame()
    line.setObjectName('divider')
    return line


class AdvancePositionDialog(QtGui.QDialog):
    """หน้าต่างปรับระยะเยื้อง anchor รายตัว (ใช้ในโหมด "ละเอียด") — ค่าถูกอ่านตอนกดปักหมุด"""

    def __init__(self, main_panel):
        super(AdvancePositionDialog, self).__init__(main_panel)
        self.main_panel = main_panel
        self.defaults = {}
        self.row_labels = []      # (QLabel, ป้ายไทย, ป้ายอังกฤษ)
        self.section_labels = []  # (QLabel, key)
        self.reset_buttons = []   # (QPushButton, default)
        self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowStaysOnTopHint)
        self.setStyleSheet(build_stylesheet())
        self.initUI()
        self.apply_language()

    def add_section(self, layout, key, fields):
        lbl_sec = make_label('section')
        self.section_labels.append((lbl_sec, key))
        layout.addWidget(lbl_sec)
        grid = QtGui.QGridLayout()
        grid.setHorizontalSpacing(8)
        grid.setVerticalSpacing(4)
        grid.setColumnStretch(0, 1)
        for row, (attr, th, en, lo, hi, default) in enumerate(fields):
            lbl = QtGui.QLabel("")
            self.row_labels.append((lbl, th, en))
            spin = QtGui.QSpinBox()
            spin.setRange(lo, hi)
            spin.setValue(default)
            spin.setFixedWidth(72)
            spin.setAlignment(QtCore.Qt.AlignRight)
            btn_reset = make_button('reset')
            btn_reset.setText("↺")
            btn_reset.setFixedWidth(18)
            btn_reset.setVisible(False)
            btn_reset.clicked.connect(lambda *args, s=spin, d=default: s.setValue(d))
            # อ่านค่าจาก spin เอง (valueChanged มีทั้งแบบ int และ str)
            spin.valueChanged.connect(lambda *args, s=spin, b=btn_reset, d=default: b.setVisible(s.value() != d))
            setattr(self, attr, spin)
            self.defaults[attr] = default
            self.reset_buttons.append((btn_reset, default))
            grid.addWidget(lbl, row, 0)
            grid.addWidget(spin, row, 1)
            grid.addWidget(btn_reset, row, 2)
        layout.addLayout(grid)

    def initUI(self):
        root = QtGui.QVBoxLayout()
        root.setContentsMargins(16, 14, 16, 14)
        root.setSpacing(10)

        self.lbl_hint = make_label('hint', word_wrap=True)
        root.addWidget(self.lbl_hint)

        cols = QtGui.QHBoxLayout()
        cols.setSpacing(24)
        col_left = QtGui.QVBoxLayout()
        col_right = QtGui.QVBoxLayout()
        col_left.setSpacing(6)
        col_right.setSpacing(6)
        self.add_section(col_left, *ADV_SECTIONS[0])
        self.add_section(col_left, *ADV_SECTIONS[3])
        col_left.addStretch()
        self.add_section(col_right, *ADV_SECTIONS[1])
        self.add_section(col_right, *ADV_SECTIONS[2])
        col_right.addStretch()
        cols.addLayout(col_left, 1)
        cols.addLayout(col_right, 1)
        root.addLayout(cols)

        root.addWidget(make_divider())
        bottom = QtGui.QHBoxLayout()
        self.btn_reset_all = make_button('link', self.reset_all_offsets)
        self.btn_run_from_adv = make_button('primary', self.main_panel.run_anchor_process)
        bottom.addWidget(self.btn_reset_all)
        bottom.addStretch()
        bottom.addWidget(self.btn_run_from_adv)
        root.addLayout(bottom)
        self.setLayout(root)

    def reset_all_offsets(self):
        for attr, default in self.defaults.items():
            getattr(self, attr).setValue(default)

    def apply_language(self):
        lang = self.main_panel.lang
        t = UI_TEXT[lang]
        self.setWindowTitle(t['adv_win_title'])
        self.lbl_hint.setText(t['adv_hint'])
        for lbl, key in self.section_labels:
            lbl.setText(t[key].upper() if lang == 'en' else t[key])
        for lbl, th, en in self.row_labels:
            lbl.setText(th if lang == 'th' else en)
        for btn, default in self.reset_buttons:
            btn.setToolTip(t['adv_reset_one'].format(default))
        self.btn_reset_all.setText(t['adv_reset_all'])
        self.btn_run_from_adv.setText(t['btn_run_main'])


class F0NTAutotunePanel(QtGui.QDialog):
    """
    Main F0NT Autotune Dialog (Clean, Minimal, Ultra-Friendly UI)
    """
    def __init__(self):
        super(F0NTAutotunePanel, self).__init__()
        self.lang = 'th'
        self.cancel_requested = False
        self.overwrite_anchors = True
        self._error_counts = {}
        self.font_error = ""

        self.fg_font = None
        self.fl_pkg = None
        self.fl_font = None
        self.adv_dialog = None
        self._button_groups = []

        self.refresh_font_context()
        self.initUI()
        self.adv_dialog = AdvancePositionDialog(self)

        self.apply_language()
        # เปิดหน้าต่าง: ดึงความสูงจากตัวแรกที่ดึงได้ (ก -> ด -> บ -> อ) ตัวที่ไม่พบหรือไม่มี outline ข้ามไป
        for i in range(len(THAI_HEIGHT_SOURCES)):
            self.cmb_height_source.setCurrentIndex(i)
            if self.fetch_thai_height(quiet=True):
                break
        else:
            self.cmb_height_source.setCurrentIndex(0)

    def is_valid_fl_obj(self, obj):
        if obj is None:
            return False
        try:
            return not bool(getattr(obj, 'isNull', lambda: False)())
        except Exception:
            return True

    def safe_iter(self, col, max_items=4000):
        if not col:
            return []
        try:
            if hasattr(col, '__len__') and not hasattr(col, 'values'):
                n = len(col)
                if n > max_items:
                    n = max_items
                out = []
                for i in range(n):
                    try:
                        it = col[i]
                        if self.is_valid_fl_obj(it):
                            out.append(it)
                    except Exception:
                        pass
                return out
        except Exception:
            pass
        out = []
        try:
            for it in col:
                if len(out) >= max_items:
                    break
                if self.is_valid_fl_obj(it):
                    out.append(it)
        except Exception:
            pass
        return out

    def get_val(self, widget, default=0):
        if widget is None:
            return default
        try:
            fn_text = getattr(widget, 'text', None)
            if fn_text is not None:
                t = str(fn_text() if callable(fn_text) else fn_text).strip()
                if t and t not in ('-', '+'):
                    return int(t)
                return default
        except Exception:
            pass

        try:
            fn_val = getattr(widget, 'value', None)
            if fn_val is not None:
                v = fn_val() if callable(fn_val) else fn_val
                return int(v)
        except Exception:
            pass

        return default

    def is_checked(self, widget):
        try:
            return bool(getattr(widget, 'isChecked', lambda: False)())
        except Exception:
            return False

    def set_progress(self, percent, status_text=""):
        self.progress_bar.setValue(percent)
        if status_text:
            self.lbl_progress_status.setText(status_text)
        try:
            QtCore.QCoreApplication.processEvents()
        except Exception:
            pass

    def request_cancel(self):
        self.cancel_requested = True
        self.log("⚠️ ผู้ใช้สั่งหยุดการทำงาน (Cancelling...)" if self.lang == 'th' else "⚠️ Operation cancelled by user.")
        self.btn_stop.setEnabled(False)

    def show_help_dialog(self):
        t = UI_TEXT[self.lang]
        box = QtGui.QMessageBox(self)
        box.setWindowTitle(t['help_main_title'])
        box.setTextFormat(QtCore.Qt.RichText)
        box.setText(t['help_main_body'])
        box.exec_()

    def open_advance_position_window(self):
        if self.adv_dialog is not None:
            self.adv_dialog.show()
            self.adv_dialog.raise_()
            self.adv_dialog.activateWindow()

    def show_log(self):
        if not self.btn_log.isChecked():
            self.btn_log.setChecked(True)

    def run_diagnostics_from_menu(self):
        self.show_log()
        self.run_anchor_diagnostics()

    def initUI(self):
        self.setWindowTitle("F0NT Autotune")
        self.setMinimumWidth(440)
        self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowStaysOnTopHint)
        self.setStyleSheet(build_stylesheet())

        root = QtGui.QVBoxLayout()
        root.setContentsMargins(16, 14, 16, 14)
        root.setSpacing(12)

        # --- Header: ชื่อ + คู่มือ + เครื่องมือ + ภาษา ---
        head = QtGui.QHBoxLayout()
        head.setSpacing(6)
        self.lbl_title = make_label('title')
        self.lbl_title.setText("F0NT Autotune")
        head.addWidget(self.lbl_title)
        head.addStretch()
        self.btn_help = make_button('icon', self.show_help_dialog)
        self.btn_help.setText("?")
        self.btn_tools = make_button('icon')
        self.btn_tools.setText("⋯")
        self.menu_tools = QtGui.QMenu(self)
        self.act_diag = self.menu_tools.addAction("")
        self.act_diag.triggered.connect(self.run_diagnostics_from_menu)
        self.act_scan = self.menu_tools.addAction("")
        self.act_scan.triggered.connect(self.scan_thai_inventory)
        self.act_copy_words = self.menu_tools.addAction("")
        self.act_copy_words.triggered.connect(self.copy_test_words)
        self.menu_tools.addSeparator()
        self.act_debug = self.menu_tools.addAction("")
        self.act_debug.setCheckable(True)
        self.btn_tools.setMenu(self.menu_tools)
        lang_box, (self.btn_lang_th, self.btn_lang_en) = make_segmented(self, 2)
        self.btn_lang_th.setText("TH")
        self.btn_lang_en.setText("EN")
        self.btn_lang_th.setChecked(True)
        self.btn_lang_th.clicked.connect(lambda *args: self.set_language('th'))
        self.btn_lang_en.clicked.connect(lambda *args: self.set_language('en'))
        head.addWidget(self.btn_help)
        head.addWidget(self.btn_tools)
        head.addSpacing(4)
        head.addWidget(lang_box)
        root.addLayout(head)

        # --- ฟอร์มหลัก ---
        form = QtGui.QGridLayout()
        form.setHorizontalSpacing(14)
        form.setVerticalSpacing(8)
        form.setColumnStretch(1, 1)

        self.lbl_scope = make_label('formLabel')
        scope_box, (self.btn_scope_font, self.chk_selected_only) = make_segmented(self, 2)
        self.btn_scope_font.setChecked(True)
        self.chk_selected_only.toggled.connect(self.update_scope_badge)
        form.addWidget(self.lbl_scope, 0, 0)
        form.addWidget(scope_box, 0, 1)

        self.chk_all_masters = QtGui.QCheckBox("")
        form.addWidget(self.chk_all_masters, 1, 1)

        self.lbl_mode = make_label('formLabel')
        mode_row = QtGui.QHBoxLayout()
        mode_row.setSpacing(10)
        mode_box, (self.rb_standard, self.rb_advanced) = make_segmented(self, 2)
        self.rb_advanced.setChecked(True)
        self.rb_advanced.toggled.connect(self.toggle_anchor_mode_ui)
        self.btn_open_adv = make_button('link', self.open_advance_position_window)
        mode_row.addWidget(mode_box)
        mode_row.addWidget(self.btn_open_adv)
        mode_row.addStretch()
        form.addWidget(self.lbl_mode, 2, 0)
        form.addLayout(mode_row, 2, 1)

        self.lbl_thai_height = make_label('formLabel')
        height_row = QtGui.QHBoxLayout()
        height_row.setSpacing(6)
        self.txt_thai_height = QtGui.QLineEdit("")
        self.txt_thai_height.setFixedWidth(56)
        self.txt_thai_height.setAlignment(QtCore.Qt.AlignRight)
        self.txt_thai_height.setValidator(QtGui.QIntValidator(1, 5000, self.txt_thai_height))
        self.cmb_height_source = QtGui.QComboBox()
        self.cmb_height_source.addItems([label for label, _ in THAI_HEIGHT_SOURCES])
        self.btn_fetch_height = make_button('icon', lambda *args: self.fetch_thai_height())
        self.btn_fetch_height.setText("↻")
        height_row.addWidget(self.txt_thai_height)
        height_row.addWidget(self.cmb_height_source)
        height_row.addWidget(self.btn_fetch_height)
        height_row.addStretch()
        form.addWidget(self.lbl_thai_height, 3, 0)
        form.addLayout(height_row, 3, 1)
        root.addLayout(form)

        # --- ตัวเลือกเพิ่มเติม (พับไว้) ---
        more_box = QtGui.QWidget()
        more_lay = QtGui.QVBoxLayout(more_box)
        more_lay.setContentsMargins(18, 0, 0, 0)
        more_lay.setSpacing(6)
        self.chk_zero_mark = QtGui.QCheckBox("")
        self.chk_zero_mark.setChecked(True)
        self.chk_overwrite_anchor = QtGui.QCheckBox("")
        self.chk_overwrite_anchor.setChecked(True)
        self.chk_clear_old_anc = QtGui.QCheckBox("")
        self.chk_clean_old_fea = QtGui.QCheckBox("")
        self.chk_gdef_class = QtGui.QCheckBox("")
        for chk in (self.chk_zero_mark, self.chk_overwrite_anchor, self.chk_clear_old_anc,
                    self.chk_clean_old_fea, self.chk_gdef_class):
            more_lay.addWidget(chk)
        self.btn_more = make_disclosure(self, more_box)
        root.addWidget(self.btn_more)
        root.addWidget(more_box)

        # --- ปุ่มหลัก + คำสั่งรอง ---
        self.btn_anchor = make_button('primary', self.run_anchor_process)
        root.addWidget(self.btn_anchor)
        actions = QtGui.QHBoxLayout()
        self.btn_assign_gdef_now = make_button('link', self.assign_gdef_classes_action)
        self.btn_clear_anc_now = make_button('dangerLink', self.clear_all_anchors_action)
        actions.addWidget(self.btn_assign_gdef_now)
        actions.addStretch()
        actions.addWidget(self.btn_clear_anc_now)
        root.addLayout(actions)

        # --- สถานะ ---
        root.addWidget(make_divider())
        self.progress_bar = QtGui.QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setTextVisible(False)
        root.addWidget(self.progress_bar)
        status_row = QtGui.QHBoxLayout()
        self.lbl_progress_status = make_label('status')
        self.btn_stop = make_button('link', self.request_cancel)
        self.btn_stop.setEnabled(False)
        status_row.addWidget(self.lbl_progress_status, 1)
        status_row.addWidget(self.btn_stop)
        root.addLayout(status_row)
        self.lbl_next_step = make_label('hint', word_wrap=True)
        root.addWidget(self.lbl_next_step)

        # --- Log (พับไว้) ---
        self.log_box = QtGui.QTextEdit()
        self.log_box.setReadOnly(True)
        self.log_box.setMinimumHeight(150)
        log_row = QtGui.QHBoxLayout()
        self.btn_log = make_disclosure(self, self.log_box)
        self.btn_clear_log = make_button('link', lambda *args: self.log_box.clear())
        log_row.addWidget(self.btn_log)
        log_row.addStretch()
        log_row.addWidget(self.btn_clear_log)
        root.addLayout(log_row)
        root.addWidget(self.log_box)

        self.setLayout(root)

    def toggle_anchor_mode_ui(self):
        self.btn_open_adv.setVisible(self.is_checked(self.rb_advanced))

    def update_scope_badge(self):
        t = UI_TEXT[self.lang]
        self.btn_anchor.setText(t['btn_run_main_sel'] if self.is_checked(self.chk_selected_only) else t['btn_run_main'])

    def set_language(self, lang):
        self.lang = lang
        self.apply_language()

    def apply_language(self):
        t = UI_TEXT[self.lang]
        self.btn_lang_th.setChecked(self.lang == 'th')
        self.btn_lang_en.setChecked(self.lang == 'en')
        self.setWindowTitle(t['app_title'])
        self.btn_help.setToolTip(t['tip_help'])
        self.btn_tools.setToolTip(t['tip_tools'])
        self.act_diag.setText(t['menu_diag'])
        self.act_scan.setText(t['menu_scan'])
        self.act_copy_words.setText(t['menu_copy_words'])
        self.act_debug.setText(t['menu_debug'])

        self.lbl_scope.setText(t['lbl_scope'])
        self.btn_scope_font.setText(t['scope_font'])
        self.chk_selected_only.setText(t['scope_sel'])
        self.chk_all_masters.setText(t['chk_all_masters'])
        self.lbl_mode.setText(t['lbl_mode'])
        self.rb_standard.setText(t['rb_std'])
        self.rb_advanced.setText(t['rb_adv'])
        self.rb_standard.setToolTip(t['tip_mode'])
        self.rb_advanced.setToolTip(t['tip_mode'])
        self.btn_open_adv.setText(t['btn_open_adv'])
        self.lbl_thai_height.setText(t['lbl_thai_height'])
        self.txt_thai_height.setToolTip(t['tip_thai_height'])
        self.btn_fetch_height.setToolTip(t['tip_fetch_height'])

        self.btn_more.setText(t['more_options'])
        self.chk_zero_mark.setText(t['chk_zero'])
        self.chk_overwrite_anchor.setText(t['chk_ow_anc'])
        self.chk_clear_old_anc.setText(t['chk_clr_anc'])
        self.chk_clean_old_fea.setText(t['chk_clean_old_fea'])
        self.chk_gdef_class.setText(t['chk_gdef_class'])

        self.btn_assign_gdef_now.setText(t['btn_assign_gdef_now'])
        self.btn_clear_anc_now.setText(t['btn_clear_anc_now'])
        self.lbl_progress_status.setText(t['ready_status'])
        self.lbl_next_step.setText(t['next_step_init'])
        self.btn_stop.setText(t['btn_stop'])
        self.btn_log.setText(t['log_toggle'])
        self.btn_clear_log.setText(t['btn_clear_log'])

        self.update_scope_badge()
        self.toggle_anchor_mode_ui()
        if self.adv_dialog is not None:
            self.adv_dialog.apply_language()

    def refresh_font_context(self):
        """fg_font = fgFont (FontGate), fl_pkg = flPackage (FontLab) ของฟอนต์ที่เปิดอยู่ หรือ None"""
        self.fg_font = None
        self.fl_pkg = None
        try:
            self.fg_font = fl6.CurrentFont()
            if self.fg_font is not None:
                self.fl_pkg = fl6.flPackage(self.fg_font)
        except Exception as e:
            self.font_error = "{}: {}".format(type(e).__name__, e)
        self.fl_font = self.fl_pkg

    def log(self, text):
        self.log_box.append(str(text))

    def report(self, text):
        """บันทึกผลลง log และแสดงบรรทัดแรกที่แถบสถานะ (log อาจพับอยู่)"""
        self.log(text)
        line = str(text).splitlines()[0] if text else ""
        for emoji, symbol in STATUS_SYMBOLS:
            if line.startswith(emoji):
                line = symbol + line[len(emoji):]
                break
        self.lbl_progress_status.setText(line.strip())

    def log_error(self, where, exc, detail=""):
        """แสดง error จริงใน log (แต่ละจุดแสดงไม่เกิน 3 ครั้งต่อการรัน แล้วสรุปจำนวนตอนจบ)"""
        key = (where, type(exc).__name__)
        n = self._error_counts.get(key, 0) + 1
        self._error_counts[key] = n
        self.show_log()
        if n <= 3:
            self.log("<span style='color: #e5675f;'>❌ {}{}: {}: {}</span>".format(
                where, " [" + detail + "]" if detail else "", type(exc).__name__, exc))

    def error_total(self):
        return sum(self._error_counts.values())

    def debug_log(self, text):
        if self.is_checked(self.act_debug):
            self.log_box.append("<span style='color: #38bdf8;'>[DEBUG] " + str(text) + "</span>")

    def get_cap_height(self):
        try:
            val = float(_get(self.fl_pkg, 'capsHeight_value'))
            if val > 0:
                return val
        except Exception as e:
            self.log_error("capsHeight_value", e)
        self.log("⚠️ อ่าน Caps Height ไม่ได้ ใช้ค่า 700" if self.lang == 'th' else "⚠️ Caps Height unavailable, using 700")
        return 700.0

    def get_upm(self):
        try:
            val = float(_get(self.fl_pkg, 'upm'))
            if val > 0:
                return val
        except Exception as e:
            self.log_error("upm", e)
        self.log("⚠️ อ่าน UPM ไม่ได้ ใช้ค่า 1000" if self.lang == 'th' else "⚠️ UPM unavailable, using 1000")
        return 1000.0

    def get_upm_scale(self):
        return self.get_upm() / 1000.0

    def find_glyph_by_code(self, code):
        """glyph ตัวหลัก (ชื่อไม่มี suffix) ของ Unicode นี้ — หาจาก Unicode ก่อน
        ถ้าไม่มี glyph ไหนผูก Unicode นี้ไว้ หาจากชื่อแทน (เช่น uni0E01, kokai, kokai-thai) — ไม่พบคืน None"""
        by_name = None
        for g in self.fg_font.glyphs:
            name = _get_name(g)
            if '.' in name:
                continue
            try:
                if code in list(g.unicodes):
                    return g
            except Exception:
                pass
            if by_name is None:
                u, sfx = self.resolve_name_to_unicode(name)
                if u == code and not sfx:
                    by_name = g
        return by_name

    def fetch_thai_height(self, quiet=False):
        """อ่านขอบบนของ outline ตัวอักษรที่เลือก (ก / ด / บ / อ) ใน master ปัจจุบัน แล้วใส่ลงช่องความสูง
        คืนค่าความสูง หรือ None ถ้าอ่านไม่ได้"""
        label, code = THAI_HEIGHT_SOURCES[_get(self.cmb_height_source, 'currentIndex')]
        self.refresh_font_context()
        if self.fg_font is None:
            if not quiet:
                self.log("⚠️ ไม่พบฟอนต์ที่เปิดอยู่" if self.lang == 'th' else "⚠️ No active font")
            return None

        target = None
        try:
            target = self.find_glyph_by_code(code)
        except Exception as e:
            self.log_error("fgFont.glyphs", e)

        if target is None:
            if not quiet:
                self.log("⚠️ ไม่พบ glyph '{}' (U+{:04X}) ในฟอนต์".format(label, code) if self.lang == 'th'
                         else "⚠️ Glyph '{}' (U+{:04X}) not found".format(label, code))
            return None

        _, _, _, fl_layer = self.get_active_layers(target, need_fl_layer=True)
        x_min, y_min, w, h = self.get_layer_bbox(fl_layer)
        if h <= 0:
            if not quiet:
                self.log("⚠️ glyph '{}' ไม่มี outline".format(label) if self.lang == 'th'
                         else "⚠️ Glyph '{}' has no outline".format(label))
            return None

        height = int(round(y_min + h))
        self.txt_thai_height.setText(str(height))
        if not quiet:
            self.log("📏 ความสูงพยัญชนะไทย = {} (จากขอบบนของ '{}' ใน master {})".format(
                height, label, self.get_master_layer_name()) if self.lang == 'th'
                else "📏 Thai consonant height = {} (top of '{}', master {})".format(
                height, label, self.get_master_layer_name()))
        return height

    def get_thai_height(self):
        """ค่าจากช่อง "ความสูงพยัญชนะไทย" — ถ้าว่าง ดึงจากตัวอักษรที่เลือก ถ้ายังไม่ได้ ใช้ Caps Height"""
        val = self.get_val(self.txt_thai_height, 0)
        if val > 0:
            return float(val)
        fetched = self.fetch_thai_height()
        if fetched:
            return float(fetched)
        self.log("⚠️ ใช้ Caps Height แทนความสูงพยัญชนะไทย" if self.lang == 'th'
                 else "⚠️ Using Caps Height as Thai consonant height")
        return self.get_cap_height()

    def get_other_master_layers(self, fl_glyph, current_layer):
        """flLayer ของ master อื่นทั้งหมดใน glyph (ข้าม mask / layer ที่ไม่ใช่ master และ layer ปัจจุบัน)"""
        out = []
        if fl_glyph is None:
            return out
        try:
            cur_name = _get(current_layer, 'name') if current_layer is not None else None
            for lyr in fl_glyph.layers:
                if not _get(lyr, 'isMasterLayer') or _get(lyr, 'isMaskLayer'):
                    continue
                if _get(lyr, 'name') == cur_name:
                    continue
                out.append(lyr)
        except Exception as e:
            self.log_error("master layers", e, _get_name(fl_glyph))
        return out

    def parse_unicode_value(self, val):
        if val is None:
            return None
        if isinstance(val, int):
            return val if val > 0 else None
        try:
            val_str = str(val).strip()
            if not val_str:
                return None
            if val_str.startswith('0x') or val_str.startswith('0X'):
                return int(val_str, 16)
            if val_str.isdigit():
                return int(val_str, 10)
            if len(val_str) == 1:
                return ord(val_str)
        except Exception:
            pass
        return None

    def resolve_name_to_unicode(self, raw_name):
        if not raw_name:
            return None, ""
        clean = raw_name.strip()
        base = clean
        suffix = ""
        if '.' in clean:
            parts = clean.split('.', 1)
            base = parts[0]
            suffix = '.' + parts[1]
            if suffix.lower() == '.thai':
                base = base + '-thai'
                suffix = ""

        lower_base = base.lower()
        if lower_base in THAI_NAME_TO_UNICODE:
            return THAI_NAME_TO_UNICODE[lower_base], suffix

        norm = lower_base.replace('_', '').replace('-', '')
        if norm in THAI_NAME_TO_UNICODE:
            return THAI_NAME_TO_UNICODE[norm], suffix

        if lower_base.endswith('-thai'):
            th_key = lower_base[:-5]
            if th_key in THAI_NAME_TO_UNICODE:
                return THAI_NAME_TO_UNICODE[th_key], suffix
            norm_th = th_key.replace('_', '').replace('-', '')
            if norm_th in THAI_NAME_TO_UNICODE:
                return THAI_NAME_TO_UNICODE[norm_th], suffix

        for pfx in ('uni', 'u', 'u+'):
            if lower_base.startswith(pfx):
                hex_part = lower_base[len(pfx):]
                if len(hex_part) == 4:
                    try:
                        return int(hex_part, 16), suffix
                    except Exception:
                        pass
        return None, suffix

    def get_glyph_unicode_and_suffix(self, fg_glyph, fl_glyph=None):
        raw_name = ""
        for g in (fg_glyph, fl_glyph):
            if g is not None:
                name_val = getattr(g, 'name', "")
                raw_name = str(name_val() if callable(name_val) else name_val)
                if raw_name:
                    break

        for g in (fg_glyph, fl_glyph):
            if g is not None:
                for attr in ('unicodes', 'unicode'):
                    if hasattr(g, attr):
                        val = getattr(g, attr)
                        val = val() if callable(val) else val
                        if isinstance(val, (list, tuple)) and len(val) > 0:
                            u = self.parse_unicode_value(val[0])
                            if u:
                                sfx = ('.' + raw_name.split('.', 1)[1]) if '.' in raw_name else ""
                                return u, sfx, raw_name
                        else:
                            u = self.parse_unicode_value(val)
                            if u:
                                sfx = ('.' + raw_name.split('.', 1)[1]) if '.' in raw_name else ""
                                return u, sfx, raw_name

        u, sfx = self.resolve_name_to_unicode(raw_name)
        return u, sfx, raw_name

    def get_glyph_unicode(self, fg_glyph, fl_glyph=None):
        u, _, _ = self.get_glyph_unicode_and_suffix(fg_glyph, fl_glyph)
        return u

    def get_all_font_glyphs(self):
        """list ของ fgGlyph ตามขอบเขต: ทั้งฟอนต์ หรือเฉพาะ Glyph ที่เปิดอยู่ (ถ้าเลือกไว้ใน Debug)"""
        self.refresh_font_context()
        if self.fg_font is None or self.fl_pkg is None:
            return []

        if self.is_checked(self.chk_selected_only):
            try:
                curr_g = fl6.CurrentGlyph()
            except Exception as e:
                self.log_error("CurrentGlyph()", e)
                curr_g = None
            return [curr_g] if curr_g is not None else []

        try:
            return list(self.fg_font.glyphs)
        except Exception as e:
            self.log_error("fgFont.glyphs", e)
            return []

    def get_master_layer_name(self):
        try:
            name = _get(self.fl_pkg, 'master')
            return str(name) if name else None
        except Exception as e:
            self.log_error("flPackage.master", e)
            return None

    def get_active_layers(self, item, need_fl_layer=False):
        """คืน (fg_glyph, fl_glyph, None, fl_layer) — fl_layer คือ layer ของ master ที่เปิดอยู่"""
        fg_glyph = item
        fl_layer = None
        try:
            fl_glyph = fl6.flGlyph(fg_glyph, self.fg_font)
        except Exception as e:
            self.log_error("flGlyph()", e, _get_name(fg_glyph))
            return fg_glyph, None, None, None

        if need_fl_layer:
            master = self.get_master_layer_name()
            try:
                if master:
                    fl_layer = fl_glyph.findLayer(master)
                if fl_layer is None:
                    fl_layer = _get(fl_glyph, 'activeLayer')
            except Exception as e:
                self.log_error("findLayer / activeLayer", e, _get_name(fl_glyph))
        return fg_glyph, fl_glyph, None, fl_layer

    def get_layer_bbox(self, fl_layer):
        """(x_min, y_min, w, h) ของเส้นจริง (ink) — คืน (0, 0, 0, 0) ถ้า layer ว่าง
        วัดจาก contour (getContours -> QPainterPath) เพราะ flLayer.boundingBox อาจกว้างกว่าเส้นจริง
        (พบใน FontLab 8.4.2 — น่าจะรวม anchor) ถ้ามี component หรือไม่มี contour จึงใช้ boundingBox แทน"""
        if fl_layer is None:
            return (0.0, 0.0, 0.0, 0.0)
        try:
            if not any(_get(s, 'isComponent') for s in fl_layer.shapes):
                contours = list(fl_layer.getContours())
                if contours:
                    path = QtGui.QPainterPath()
                    for contour in contours:
                        path.addPath(contour.path())
                    r = path.boundingRect()
                    return (float(r.x()), float(r.y()), float(r.width()), float(r.height()))
            r = _get(fl_layer, 'boundingBox')
            return (float(r.x()), float(r.y()), float(r.width()), float(r.height()))
        except Exception as e:
            self.log_error("bounding box", e, _get_name(fl_layer))
            return (0.0, 0.0, 0.0, 0.0)

    def notify_glyph_updated(self, fl_glyph):
        if fl_glyph is None or self.fl_pkg is None:
            return
        try:
            fl_glyph.update()
        except Exception as e:
            self.log_error("flGlyph.update()", e)
        try:
            fl6.flItems.notifyGlyphUpdated(self.fl_pkg.id, fl_glyph.id)
        except Exception as e:
            self.log_error("notifyGlyphUpdated", e)

    def update_fontlab_viewport(self):
        try:
            fl6.Update()
        except Exception as e:
            self.log_error("fontlab.Update()", e)

    def confirm_action(self, text_th, text_en):
        res = QtGui.QMessageBox.question(
            self, "F0NT Autotune", text_th if self.lang == 'th' else text_en,
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No
        )
        return res == QtGui.QMessageBox.Yes

    def run_anchor_diagnostics(self):
        """ตรวจระบบแบบอ่านอย่างเดียว (ไม่แก้ไขฟอนต์)"""
        self.log_box.clear()
        self._error_counts = {}
        self.log("🔍 เริ่มการวินิจฉัยระบบ Anchor (อ่านอย่างเดียว)..." if self.lang == 'th' else "🔍 Running Anchor Diagnostics (read-only)...")

        raw_glyphs = self.get_all_font_glyphs()
        self.log("1. ตรวจสอบการเชื่อมต่อโมเดลฟอนต์:")
        self.log("   - fgFont: {}, flPackage: {}".format(
            type(self.fg_font).__name__ if self.fg_font is not None else "None",
            type(self.fl_pkg).__name__ if self.fl_pkg is not None else "None"))
        if self.fl_pkg is None:
            self.log("⚠️ ไม่พบฟอนต์ที่เปิดอยู่ กรุณาเปิดฟอนต์ใน FontLab ก่อนรัน")
            return
        self.log("   - Master ปัจจุบัน: {}".format(self.get_master_layer_name()))
        self.log("   - จำนวน Glyph ทั้งหมดในขอบเขต: {}".format(len(raw_glyphs)))
        self.log("   - UPM: {}, Caps Height: {}, ความสูงพยัญชนะไทยที่จะใช้: {}".format(
            self.get_upm(), self.get_cap_height(), self.get_thai_height()))

        sample_item = None
        for item in raw_glyphs:
            u, _, _ = self.get_glyph_unicode_and_suffix(item)
            if u == 0x0E01:
                sample_item = item
                break
        if sample_item is None and raw_glyphs:
            sample_item = raw_glyphs[0]
        if sample_item is None:
            self.log("⚠️ ไม่พบ Glyph ในขอบเขต")
            return

        fg_g, fl_g, _, fl_l = self.get_active_layers(sample_item, need_fl_layer=True)
        u, sfx, g_name = self.get_glyph_unicode_and_suffix(fg_g, fl_g)
        self.log("2. Glyph ตัวอย่าง: '{}' (U+{:04X}{})".format(g_name, u if u else 0, sfx))
        self.log("   - layer: {}".format(_get_name(fl_l) if fl_l is not None else "None"))
        bbox = self.get_layer_bbox(fl_l)
        self.log("   - Bounding Box: x_min={:.1f}, y_min={:.1f}, w={:.1f}, h={:.1f}".format(*bbox))
        try:
            self.log("   - Anchors: {}".format([_get_name(a) for a in fl_l.anchors]))
        except Exception as e:
            self.log_error("layer.anchors", e)
        try:
            self.log("   - Features ในฟอนต์: {}".format(list(self.fg_font.features.keys())))
        except Exception as e:
            self.log_error("features.keys()", e)

        if self.error_total():
            self.report("⚠️ พบข้อผิดพลาด {} ครั้ง — ส่ง log นี้กลับมาเพื่อแก้ไข".format(self.error_total()))
        else:
            self.report("✅ วินิจฉัยเสร็จ ไม่พบข้อผิดพลาด")

    def scan_thai_inventory(self):
        """นับ glyph ไทยในฟอนต์ แสดงผลที่แถบสถานะ (อ่านอย่างเดียว)"""
        raw_glyphs = self.get_all_font_glyphs()
        if not raw_glyphs:
            self.lbl_progress_status.setText("ไม่พบ Glyph ในฟอนต์ที่เปิดอยู่" if self.lang == 'th' else "No glyphs found.")
            return

        cons_count = vow_count = tone_count = alt_count = 0
        for item in raw_glyphs:
            u, sfx, _ = self.get_glyph_unicode_and_suffix(item)
            if not u or not (0x0E01 <= u <= 0x0E5B):
                continue
            if sfx:
                alt_count += 1
            elif 0x0E01 <= u <= 0x0E2E:
                cons_count += 1
            elif u in (0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39, 0x0E3A,
                       0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45):
                vow_count += 1
            elif u in (0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, 0x0E4C, 0x0E4D, 0x0E4E):
                tone_count += 1

        if self.lang == 'th':
            text = "ไทย: พยัญชนะ {}/44 · สระ {} · วรรณยุกต์/เครื่องหมาย {} · ตัวสลับ {}".format(
                cons_count, vow_count, tone_count, alt_count)
        else:
            text = "Thai: consonants {}/44 · vowels {} · tones/marks {} · alternates {}".format(
                cons_count, vow_count, tone_count, alt_count)
        self.lbl_progress_status.setText(text)
        self.log(text)

    def is_zero_width_thai_mark(self, u):
        if not u:
            return False
        return u in [
            0x0E31, 0x0E34, 0x0E35, 0x0E36, 0x0E37,
            0x0E38, 0x0E39, 0x0E3A,
            0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, 0x0E4C, 0x0E4D, 0x0E4E
        ]

    def is_mark_glyph(self, u, g_name=""):
        if not u and g_name and hasattr(self, 'resolve_name_to_unicode'):
            u, _ = self.resolve_name_to_unicode(g_name)
        if self.is_zero_width_thai_mark(u):
            return True
        if u:
            try:
                import unicodedata
                cat = unicodedata.category(chr(u))
                if cat.startswith('M'):  # Mn (Nonspacing), Mc (Combining), Me (Enclosing)
                    return True
            except Exception:
                pass
        if g_name:
            lower = g_name.lower()
            for kw in ('mai', 'sara', 'phinthu', 'nikhahit', 'nikkhahit', 'thanthakhat', 'yamakkan'):
                if kw in lower and any(suffix in lower for suffix in ('.small', '.up', '.high', '.left', '.narrow', '.lowleft', '.low', '.short', '.sub')):
                    return True
            # Also check hex patterns in uni0Exx / u0Exx names for Thai marks
            for hex_code in ('0e31', '0e34', '0e35', '0e36', '0e37', '0e38', '0e39', '0e3a', '0e47', '0e48', '0e49', '0e4a', '0e4b', '0e4c', '0e4d', '0e4e'):
                if hex_code in lower:
                    return True
            if lower.endswith(('.mark', '_mark')):
                return True
        return False

    def is_ignorable_or_control_glyph(self, u, g_name):
        """Identifies non-marking, control, or special glyphs that should not be classified as Base or Mark."""
        if not g_name:
            return True
        lower = str(g_name).lower().strip()

        # 1. Standard control & non-marking glyph names
        if lower in (
            '.notdef', '.null', 'null', 'cr', 'lf', 'nonmarkingreturn', 'return', 'linefeed',
            'space', 'nbspace', 'nonbreakingspace', 'sp', 'blank',
            'zerowidthspace', 'zerowidthjoiner', 'zerowidthnonjoiner',
            'zwj', 'zwnj', 'zwsp', 'bom', 'softhyphen'
        ):
            return True

        if lower.startswith(('.notdef', '.null')):
            return True

        # 2. Unicode ranges for controls and invisible separators
        if u is not None and isinstance(u, int):
            # C0 controls (0x0000 - 0x001F)
            if 0x0000 <= u <= 0x001F:
                return True
            # Space & No-break space
            if u in (0x0020, 0x00A0):
                return True
            # C1 controls & DEL (0x007F - 0x009F)
            if 0x007F <= u <= 0x009F:
                return True
            # Zero-width spaces & format controls (0x200B - 0x200F, 0x2028 - 0x202F, 0x2060 - 0x206F, 0xFEFF)
            if (0x200B <= u <= 0x200F) or (0x2028 <= u <= 0x202F) or (0x2060 <= u <= 0x206F) or u == 0xFEFF:
                return True

        # 3. Hex pattern names for control / space unicodes (e.g., uni0000 - uni001F, uni000D, uni0020, uni00A0)
        if lower.startswith('uni') and len(lower) == 7:
            try:
                val = int(lower[3:], 16)
                if (0x0000 <= val <= 0x001F) or val in (0x0020, 0x00A0) or (0x007F <= val <= 0x009F) or (0x200B <= val <= 0x200F) or val == 0xFEFF:
                    return True
            except Exception:
                pass
        elif lower.startswith('u000') and len(lower) == 5:
            return True

        return False

    def escape_fea_glyph_name(self, name):
        """Escapes glyph name with backslash if it matches an AFDKO reserved keyword or starts with a digit/period."""
        if not name:
            return ""
        g = str(name).strip()
        if not g:
            return ""
        if g in AFDKO_RESERVED_WORDS:
            return "\\" + g
        if g[0].isdigit() or g.startswith('.'):
            return "\\" + g
        return g

    def build_gdef_table_code(self, classes):
        """table GDEF จาก dict {OT_CLASS_*: [glyph names]} (ค่า otGlyphClass ของ FontLab)"""
        def glyph_list(cls):
            names = sorted(set(self.escape_fea_glyph_name(g) for g in classes.get(cls, [])
                               if g and not self.is_ignorable_or_control_glyph(None, g)))
            return "[{}]".format(" ".join(names)) if names else ""

        parts = [glyph_list(OT_CLASS_BASE), glyph_list(OT_CLASS_LIGATURE), glyph_list(OT_CLASS_MARK), ""]
        if not any(parts):
            return ""
        lines = [
            "table GDEF {",
            "    # Auto-Generated by F0NT Autotune (from FontLab OT glyph classes)",
            "    # GlyphClassDef: @bases, @ligatures, @marks, @components",
            "    GlyphClassDef {};".format(", ".join(parts)),
            "} GDEF;"
        ]
        return "\n".join(lines)

    def collect_gdef_classes(self, raw_glyphs):
        """อ่าน flGlyph.otGlyphClass ของทุก glyph -> dict {ค่า class: [ชื่อ glyph]} — ไม่แก้ไขฟอนต์"""
        classes = {}
        for item in raw_glyphs:
            g_name = _get_name(item)
            try:
                cls = int(fl6.flGlyph(item, self.fg_font).otGlyphClass)
            except Exception as e:
                self.log_error("otGlyphClass", e, g_name)
                continue
            classes.setdefault(cls, []).append(g_name)
        return classes

    def find_thai_class_mismatches(self, raw_glyphs):
        """glyph ไทยที่ otGlyphClass ไม่ตรงกับที่ควรเป็น: mark ไทย -> Mark (3), ตัวอื่นที่เป็น Mark -> Base (1)
        คืน list ของ (fl_glyph, name, current, expected)"""
        out = []
        for item in raw_glyphs:
            u, _, g_name = self.get_glyph_unicode_and_suffix(item)
            if not u or not (0x0E01 <= u <= 0x0E5B) or self.is_ignorable_or_control_glyph(u, g_name):
                continue
            try:
                fl_glyph = fl6.flGlyph(item, self.fg_font)
                current = int(fl_glyph.otGlyphClass)
            except Exception as e:
                self.log_error("otGlyphClass", e, g_name)
                continue
            if self.is_mark_glyph(u, g_name):
                if current != OT_CLASS_MARK:
                    out.append((fl_glyph, g_name, current, OT_CLASS_MARK))
            elif current == OT_CLASS_MARK:
                out.append((fl_glyph, g_name, current, OT_CLASS_BASE))
        return out

    def assign_gdef_classes_action(self):
        """ปุ่ม "ตรวจ OT Class ไทย": หา glyph ไทยที่ OT Class ไม่ตรง แล้วแก้ otGlyphClass เมื่อผู้ใช้ยืนยัน"""
        self._error_counts = {}
        raw_glyphs = self.get_all_font_glyphs()
        if not raw_glyphs:
            self.log("⚠️ ไม่พบฟอนต์ที่เปิดอยู่ใน FontLab" if self.lang == 'th' else "⚠️ No active font open in FontLab")
            return

        mismatches = self.find_thai_class_mismatches(raw_glyphs)
        if not mismatches:
            self.report("✅ OT Class ของ glyph ไทยถูกต้องทั้งหมด (สระลอย/วรรณยุกต์ = Mark)" if self.lang == 'th'
                     else "✅ All Thai OT glyph classes are correct (above/below marks = Mark)")
            return

        lines = ["{}: {} → {}".format(name, OT_CLASS_NAMES.get(cur, cur), OT_CLASS_NAMES[exp])
                 for _, name, cur, exp in mismatches]
        self.report("🏷️ OT Class ที่ไม่ตรง {} ตัว:\n- {}".format(len(lines), "\n- ".join(lines)) if self.lang == 'th'
                 else "🏷️ {} mismatched OT classes:\n- {}".format(len(lines), "\n- ".join(lines)))
        if not self.confirm_action(
            "แก้ OT Class ของ glyph ไทย {} ตัวตามรายการใน log?\n(FontLab อาจปิดโหมด Auto ของ glyph ที่ถูกแก้)".format(len(lines)),
            "Change the OT class of {} Thai glyphs as listed in the log?\n(FontLab may turn off Auto for these glyphs)".format(len(lines))
        ):
            return

        changed = 0
        for fl_glyph, name, cur, exp in mismatches:
            try:
                fl_glyph.otGlyphClass = exp
                if int(fl_glyph.otGlyphClass) == exp:
                    changed += 1
                    self.notify_glyph_updated(fl_glyph)
                else:
                    self.log("⚠️ {}: ตั้งค่าแล้วแต่อ่านกลับได้ {}".format(name, fl_glyph.otGlyphClass))
            except Exception as e:
                self.log_error("otGlyphClass =", e, name)
        self.update_fontlab_viewport()
        self.report("🏷️ แก้ OT Class สำเร็จ {} / {} ตัว".format(changed, len(mismatches)) if self.lang == 'th'
                 else "🏷️ OT class changed: {} / {}".format(changed, len(mismatches)))

    def clear_layer_anchors(self, fl_layer, names=None):
        """ลบ anchor ใน layer — names=None ลบทั้งหมด หรือส่ง set ของชื่อที่จะลบ  คืนจำนวนที่ลบ"""
        if fl_layer is None:
            return 0
        removed = 0
        try:
            for a in list(fl_layer.anchors):
                if names is None or _get_name(a) in names:
                    fl_layer.removeAnchor(a)
                    removed += 1
        except Exception as e:
            self.log_error("removeAnchor", e, _get_name(fl_layer))
        return removed

    def remove_conflicting_anchors(self, fl_layer, is_bottom_mark=False, is_top_mark=False, is_base_consonant=False):
        if is_bottom_mark:
            # สระล่างต้องไม่มี _top หรือ top ใดๆ ทั้งสิ้น
            prefixes = ('_top', 'top')
        elif is_top_mark:
            # สระบน/วรรณยุกต์ต้องไม่มี _bottom หรือ bottom ใดๆ
            prefixes = ('_bottom', 'bottom')
        elif is_base_consonant:
            # พยัญชนะต้องไม่มี mark anchor ที่ขึ้นต้นด้วยขีดล่าง (_top, _bottom)
            prefixes = ('_top', '_bottom')
        else:
            return
        try:
            names = set(n for n in (_get_name(a) for a in fl_layer.anchors) if n.startswith(prefixes))
        except Exception as e:
            self.log_error("layer.anchors", e, _get_name(fl_layer))
            return
        if names:
            self.clear_layer_anchors(fl_layer, names)

    def clear_all_anchors_action(self):
        """ปุ่ม "ล้าง Anchor ทันที": ลบ anchor ทั้งหมดเฉพาะ glyph ภาษาไทย (U+0E01–0E5B)"""
        self._error_counts = {}
        raw_glyphs = self.get_all_font_glyphs()
        if not raw_glyphs:
            self.log("ไม่พบ Glyph ในฟอนต์ที่เปิดอยู่" if self.lang == 'th' else "No glyphs found.")
            return

        thai_glyphs = []
        for item in raw_glyphs:
            u, _, _ = self.get_glyph_unicode_and_suffix(item)
            if u and 0x0E01 <= u <= 0x0E5B:
                thai_glyphs.append(item)

        is_all_masters = self.is_checked(self.chk_all_masters)
        if not thai_glyphs or not self.confirm_action(
            "ลบ Anchor ทั้งหมดใน Glyph ไทย {} ตัว{}?\nสคริปต์ไม่มี Undo — แนะนำให้ทำกับไฟล์สำเนา".format(
                len(thai_glyphs), " (ทุก Master)" if is_all_masters else " (เฉพาะ Master ปัจจุบัน)"),
            "Remove ALL anchors from {} Thai glyphs{}?\nNo undo — work on a copy.".format(
                len(thai_glyphs), " (all masters)" if is_all_masters else " (current master)")
        ):
            return

        total_cleared = 0
        for item in thai_glyphs:
            fg_g, fl_g, _, fl_l = self.get_active_layers(item, need_fl_layer=True)
            total_cleared += self.clear_layer_anchors(fl_l)
            if is_all_masters:
                for ex_fl in self.get_other_master_layers(fl_g, fl_l):
                    total_cleared += self.clear_layer_anchors(ex_fl)
            self.notify_glyph_updated(fl_g)

        self.update_fontlab_viewport()
        if self.lang == 'th':
            self.report("🗑️ ล้าง Anchor ใน Glyph ไทยแล้ว {} จุด".format(total_cleared))
        else:
            self.report("🗑️ Removed {} anchors from Thai glyphs.".format(total_cleared))
        if self.error_total():
            self.log("⚠️ พบข้อผิดพลาด {} ครั้ง".format(self.error_total()))

    def set_anchor(self, fl_layer, name, x, y):
        """ปัก anchor ชื่อ name ที่ (x, y) — ถ้ามีชื่อเดิมอยู่: ลบแล้วใส่ใหม่ (Overwrite) หรือคงของเดิมไว้
        คืน True เมื่อ layer มี anchor ชื่อนี้หลังทำงาน"""
        if fl_layer is None:
            return False
        try:
            old = fl_layer.findAnchor(name)
            if old is not None:
                if not self.overwrite_anchors:
                    return True
                fl_layer.removeAnchor(old)
            anc = fl6.flPinPoint(QtCore.QPointF(float(x), float(y)))
            anc.name = name
            anc.anchor = True
            fl_layer.addAnchor(anc)
            return True
        except Exception as e:
            self.log_error("set_anchor", e, "{} / {}".format(_get_name(fl_layer), name))
            return False

    def make_zero_width_mark(self, fl_layer):
        try:
            fl_layer.advanceWidth = 0
        except Exception as e:
            self.log_error("advanceWidth = 0", e, _get_name(fl_layer))

    def build_anchor_context(self):
        """อ่านค่าตัวเลือกและ slider ทั้งหมดครั้งเดียวก่อนเริ่มประมวลผล"""
        scale = self.get_upm_scale()
        adv = self.adv_dialog

        def off(widget, default):
            return int(round(self.get_val(widget, default) * scale))

        tone_configs = {
            'maiEk': {'name': 'top_maiEk', 'mark': '_top_maiEk', 'offset': off(adv.spin_ek, 0), 'code': 0x0E48},
            'maiTho': {'name': 'top_maiTho', 'mark': '_top_maiTho', 'offset': off(adv.spin_tho, -25), 'code': 0x0E49},
            'maiTri': {'name': 'top_maiTri', 'mark': '_top_maiTri', 'offset': off(adv.spin_tri, 0), 'code': 0x0E4A},
            'maiChattawa': {'name': 'top_maiChattawa', 'mark': '_top_maiChattawa', 'offset': off(adv.spin_chattawa, 0), 'code': 0x0E4B},
            'thanthakhat': {'name': 'top_thanthakhat', 'mark': '_top_thanthakhat', 'offset': off(adv.spin_thanthakhat, -40), 'code': 0x0E4C},
            'maitaikhu': {'name': 'top_maitaikhu', 'mark': '_top_maitaikhu', 'offset': off(adv.spin_maitaikhu, 0), 'code': 0x0E47},
            'yamakkan': {'name': 'top_yamakkan', 'mark': '_top_yamakkan', 'offset': off(adv.spin_yamakkan, 0), 'code': 0x0E4E}
        }

        return {
            'scale': scale,
            # ความสูงพยัญชนะไทย (ใช้แทน Caps Height ในทุกสูตรของต้นฉบับ)
            'cap_height': self.get_thai_height(),
            'is_adv': self.is_checked(self.rb_advanced),
            'do_zero': self.is_checked(self.chk_zero_mark),
            'do_clear_old': self.is_checked(self.chk_clear_old_anc),
            'is_dbg': self.is_checked(self.act_debug),
            'tail_shift_x': off(adv.spin_tail_shift, -75),
            'tone_configs': tone_configs,
            'tone_unicodes': [cfg['code'] for cfg in tone_configs.values()],
            # สระลอยบนและนิคหิต (6 ตัว + Y offset)
            'top_vowel_offsets': {
                0x0E31: off(adv.spin_maihanakat, 0),
                0x0E34: off(adv.spin_sarai, 0),
                0x0E35: off(adv.spin_saraii, 0),
                0x0E36: off(adv.spin_saraue, 0),
                0x0E37: off(adv.spin_sarauee, 0),
                0x0E4D: off(adv.spin_nikhahit, 0)
            },
            'upper_y_offset': off(adv.spin_upper_y, 0),
            # สระลอยล่างและพินทุ (3 ตัว + Y offset)
            'bot_vowel_offsets': {
                0x0E38: off(adv.spin_sarau, 0),
                0x0E39: off(adv.spin_sarauu, 0),
                0x0E3A: off(adv.spin_phinthu, 0)
            },
            'lower_y_offset': off(adv.spin_lower_y, 0),
            'cleared': 0
        }

    def place_layer_anchors(self, fl_layer, u, suffix, g_name, ctx, rec):
        """ปัก anchor ลง layer เดียว โดยคำนวณจาก bounding box ของ layer นั้นเอง
        rec = dict สำหรับเก็บข้อมูลสร้าง Feature (ส่ง None สำหรับ master อื่น)
        คืน True/False = ปัก anchor หลักสำเร็จหรือไม่, None = ข้าม glyph นี้"""
        scale = ctx['scale']
        cap_height = ctx['cap_height']
        is_adv = ctx['is_adv']
        tone_configs = ctx['tone_configs']

        if rec is not None and not suffix:
            if u == 0x0E33 and g_name:
                rec['sara_am'] = g_name
            elif u == 0x0E4D and g_name:
                rec['nikhahit'] = g_name
            elif u == 0x0E32 and g_name:
                rec['sara_aa'] = g_name

        is_top_vowel = u in TOP_VOWEL_UNICODES
        is_bottom_vowel = u in BOTTOM_VOWEL_UNICODES
        is_tone = u in ctx['tone_unicodes']
        is_consonant = 0x0E01 <= u <= 0x0E2E
        if not (is_top_vowel or is_bottom_vowel or is_tone or is_consonant):
            return None

        x_min, y_min, w, h = self.get_layer_bbox(fl_layer)

        if w <= 0 and self.is_zero_width_thai_mark(u):
            if is_bottom_vowel:
                x_min, y_min, w, h = (-110.0 * scale, -220.0 * scale, 120.0 * scale, 180.0 * scale)
            else:
                x_min, y_min, w, h = (-110.0 * scale, cap_height + 20.0 * scale, 120.0 * scale, 90.0 * scale)

        # Consonant fallback: If outline bounding box is empty, check advance width
        if w <= 0 and is_consonant:
            adv_w = 0.0
            try:
                adv_w = float(_get(fl_layer, 'advanceWidth'))
            except Exception as e:
                self.log_error("advanceWidth", e, g_name)
            if adv_w > 50.0:
                x_min = adv_w * 0.1
                w = adv_w * 0.8
                y_min = 0.0
                h = cap_height
                if ctx['is_dbg']:
                    self.debug_log("Consonant '{}' (U+{:04X}{}) empty bbox; used advance width fallback ({:.0f})".format(g_name, u, suffix, adv_w))

        if w <= 0:
            if ctx['is_dbg']:
                self.debug_log("Skip '{}' (U+{:04X}{}): empty bounding box".format(g_name, u, suffix))
            return None

        if ctx['do_clear_old']:
            ctx['cleared'] += self.clear_layer_anchors(fl_layer)

        if ctx['do_zero'] and self.is_zero_width_thai_mark(u):
            self.make_zero_width_mark(fl_layer)

        x_max = x_min + w
        y_max = y_min + h
        center_x = int(round(x_min + (w / 2.0)))
        ic_height = int(round(cap_height))
        iy_max = int(round(max(y_max, cap_height + 90.0 * scale)))
        iy_min = int(round(min(0.0, y_min)))

        # 1. สระบน และ นิคหิต (0x0E31, 0x0E34-0x0E37, 0x0E4D)
        if is_top_vowel:
            self.remove_conflicting_anchors(fl_layer, is_top_mark=True)

            is_base_mark = (y_max < (cap_height * 0.5))
            v_ref_y = int(round(max(0.0, y_min))) if is_base_mark else ic_height
            v_top_y = int(round(y_max + (cap_height - y_min) if is_base_mark else iy_max))

            vow_off_x = ctx['top_vowel_offsets'].get(u, 0) if is_adv else 0
            vow_off_y = ctx['upper_y_offset'] if is_adv else 0

            m_anchor_x = center_x - vow_off_x
            m_anchor_y = v_ref_y - vow_off_y

            ok = self.set_anchor(fl_layer, "_top", m_anchor_x, m_anchor_y)
            if is_adv:
                for cfg in tone_configs.values():
                    self.set_anchor(fl_layer, cfg['name'], center_x + cfg['offset'], v_top_y)
            else:
                self.set_anchor(fl_layer, "top", center_x, v_top_y)

            if rec is not None and g_name:
                rec['top_vow'].append((g_name, m_anchor_x, m_anchor_y, v_top_y, center_x))
                if suffix in SHIFTED_LEFT_SUFFIXES and u not in rec['top_vow_left']:
                    rec['top_vow_left'][u] = (g_name, suffix)
            return ok

        # 2. สระล่าง (ุ ู ฺ)
        if is_bottom_vowel:
            self.remove_conflicting_anchors(fl_layer, is_bottom_mark=True)

            bot_off_x = ctx['bot_vowel_offsets'].get(u, 0) if is_adv else 0
            bot_off_y = ctx['lower_y_offset'] if is_adv else 0

            # ตรวจสอบว่าสระล่างถูกวาดอยู่บน Baseline (y >= 0) หรือวาดใต้ Baseline อยู่แล้ว
            is_base_mark = (y_max > (10.0 * scale))
            if is_base_mark:
                # หากสระล่างถูกวาดอยู่บน Baseline:
                # ต้องตั้งจุดยึด _bottom ไว้ที่ขอบบนของสระ (y_max) + ระยะเว้นช่องไฟมาตรฐาน (25 U)
                # เพื่อให้เมื่อประกบกับ anchor 'bottom' (y: 0) ของพยัญชนะ
                # ตัวสระจะถูกเลื่อนลงไปอยู่ใต้เส้น Baseline พอดี และไม่ลอยขึ้นมาทับพยัญชนะ
                gap = int(round(25.0 * scale))
                v_ref_y = int(round(y_max + gap))
            else:
                # หากถูกวาดอยู่ที่ระดับใต้ Baseline อยู่แล้ว (เช่น y_min: -220, y_max: -30)
                v_ref_y = 0

            m_bot_x = center_x - bot_off_x
            m_bot_y = v_ref_y - bot_off_y

            ok = self.set_anchor(fl_layer, "_bottom", m_bot_x, m_bot_y)
            if rec is not None and g_name:
                rec['bot_vow'].append((g_name, m_bot_x, m_bot_y))
            return ok

        # 3. วรรณยุกต์และเครื่องหมายบน (0x0E48-0x0E4C, 0x0E47, 0x0E4E)
        if is_tone:
            self.remove_conflicting_anchors(fl_layer, is_top_mark=True)

            is_base_mark = (y_max < (cap_height * 0.5))
            t_ref_y = int(round(max(0.0, y_min))) if is_base_mark else ic_height

            ok = False
            if is_adv:
                for key, cfg in tone_configs.items():
                    if cfg['code'] == u:
                        ok = self.set_anchor(fl_layer, cfg['mark'], center_x, t_ref_y)
                        self.set_anchor(fl_layer, "_top", center_x, t_ref_y)
                        if rec is not None and g_name:
                            if not suffix:
                                rec['tones'][key] = (g_name, center_x, t_ref_y)
                            else:
                                rec['tones_alt'].setdefault(key, []).append((g_name, suffix, center_x, t_ref_y))
                        break
            else:
                ok = self.set_anchor(fl_layer, "_top", center_x, t_ref_y)
                if rec is not None and g_name and not suffix:
                    rec['tones'][g_name] = (g_name, center_x, t_ref_y)
            return ok

        # 4. พยัญชนะ (ก-ฮ) — หลบหาง ป/ฝ/ฟ/ฬ และตัดเชิง ญ/ฐ ทำงานในทุกโหมดเสมอ!
        self.remove_conflicting_anchors(fl_layer, is_base_consonant=True)
        is_tall_tail = (u in ASCENDER_TAIL_UNICODES) or (y_max > (cap_height + 70.0 * scale))
        is_desc_cut_char = (u in DESCENDER_CUT_UNICODES)
        is_desc_less_glyph = is_desc_cut_char and (suffix in DESCENDER_LESS_SUFFIXES)

        if is_tall_tail:
            body_center_x = int(round(x_min + (w * 0.42) + ctx['tail_shift_x']))
            min_safe_x = int(round(x_min + (w * 0.22)))
            base_top_x = max(min_safe_x, body_center_x)
            if rec is not None and g_name and not suffix:
                rec['tall_cons'].append(g_name)
        else:
            base_top_x = center_x

        ok = self.set_anchor(fl_layer, "top", base_top_x, ic_height)
        if is_adv:
            for cfg in tone_configs.values():
                self.set_anchor(fl_layer, cfg['name'], base_top_x + cfg['offset'], ic_height)

        if is_desc_less_glyph:
            bot_x = int(round(x_max - (w * 0.22))) if u in (0x0E0D, 0x0E10) else center_x
            bot_y = 0
            if rec is not None and g_name and u not in rec['desc_less']:
                rec['desc_less'][u] = g_name
        elif is_desc_cut_char:
            bot_x = int(round(x_max - (w * 0.22))) if u in (0x0E0D, 0x0E10) else center_x
            bot_y = iy_min if iy_min < (-20.0 * scale) else 0
            if rec is not None and g_name and not suffix:
                rec['desc_bases'][u] = g_name
        elif u in DEEP_STEM_UNICODES:
            bot_x = center_x
            bot_y = iy_min if iy_min < (-30.0 * scale) else 0
        else:
            bot_x = center_x
            bot_y = 0

        self.set_anchor(fl_layer, "bottom", bot_x, bot_y)

        if rec is not None and g_name:
            rec['cons'].append((g_name, base_top_x, ic_height, bot_x, bot_y))
        return ok

    def run_anchor_process(self):
        self._error_counts = {}
        raw_glyphs = self.get_all_font_glyphs()
        if not raw_glyphs:
            msg = "ไม่พบไฟล์ฟอนต์ที่กำลังเปิดอยู่" if self.lang == 'th' else "No active font found."
            self.log(msg)
            return

        is_all_masters = self.is_checked(self.chk_all_masters)
        if not self.confirm_action(
            "ปักหมุด Anchor ใน Glyph ไทย ({} glyph ในขอบเขต{}) และเขียน Features ลงฟอนต์\n"
            "สคริปต์ไม่มี Undo — แนะนำให้ทดสอบกับไฟล์สำเนา\nดำเนินการต่อ?".format(
                len(raw_glyphs), ", ทุก Master" if is_all_masters else ", เฉพาะ Master ปัจจุบัน"),
            "Place anchors on Thai glyphs ({} glyphs in scope{}) and write Features?\n"
            "No undo — test on a copy first.\nContinue?".format(
                len(raw_glyphs), ", all masters" if is_all_masters else ", current master")
        ):
            return

        self.cancel_requested = False
        self.btn_stop.setEnabled(True)
        self.log_box.clear()
        self.set_progress(0, "กำลังปักหมุด Anchor..." if self.lang == 'th' else "Placing Thai anchors...")

        try:
            self.overwrite_anchors = self.is_checked(self.chk_overwrite_anchor)
            do_assign_gdef = self.is_checked(self.chk_gdef_class)
            ctx = self.build_anchor_context()

            if ctx['is_dbg']:
                self.debug_log("Context: is_adv={}, cap_height={}, scale={}, tail_shift_x={}, master={}".format(
                    ctx['is_adv'], ctx['cap_height'], ctx['scale'], ctx['tail_shift_x'], self.get_master_layer_name()
                ))

            fea_records = {
                'cons': [],
                'top_vow': [],
                'bot_vow': [],
                'tones': {},
                'tones_alt': {},
                'top_vow_left': {},
                'desc_bases': {},
                'desc_less': {},
                'tall_cons': [],
                'sara_am': None,
                'nikhahit': None,
                'sara_aa': None
            }

            total = len(raw_glyphs)
            count = 0
            success_count = 0

            for idx, item in enumerate(raw_glyphs):
                if self.cancel_requested:
                    break
                if idx % 15 == 0:
                    pct = int((idx / float(max(1, total))) * 100)
                    self.set_progress(pct, "Glyph {}/{}".format(idx, total))

                u, suffix, g_name = self.get_glyph_unicode_and_suffix(item)
                if not u or not (0x0E01 <= u <= 0x0E5B):
                    continue

                fg_glyph, fl_glyph, _, fl_layer = self.get_active_layers(item, need_fl_layer=True)
                if fl_layer is None:
                    continue

                ok = self.place_layer_anchors(fl_layer, u, suffix, g_name, ctx, fea_records)
                if ok is None:
                    continue
                if is_all_masters:
                    for ex_fl in self.get_other_master_layers(fl_glyph, fl_layer):
                        self.place_layer_anchors(ex_fl, u, suffix, g_name, ctx, None)

                self.notify_glyph_updated(fl_glyph)
                count += 1
                if ok:
                    success_count += 1

            self.update_fontlab_viewport()
            self.set_progress(100, "เสร็จสิ้น" if self.lang == 'th' else "Completed")

            if self.cancel_requested:
                self.log("⚠️ หยุดกลางทาง: ปักหมุดไปแล้ว {} ตัว และไม่ได้เขียน Features".format(count)
                         if self.lang == 'th' else "⚠️ Cancelled after {} glyphs; Features not written.".format(count))
                return

            # 5. Build and inject OpenType Features (ccmp, mark, mkmk) + GDEF ใน prefix
            # โหมด glyph เดียว: ไม่เขียน Features / GDEF เพราะจะได้โค้ดจาก glyph ตัวเดียวไปทับของทั้งฟอนต์
            single_scope = self.is_checked(self.chk_selected_only)
            injected_count = 0
            if single_scope:
                self.log("ℹ️ โหมดเฉพาะ Glyph ที่เปิดอยู่: ปักหมุดอย่างเดียว ไม่เขียน Features / GDEF" if self.lang == 'th'
                         else "ℹ️ Active-glyph mode: anchors only, Features / GDEF not written")
                self.remove_empty_own_features()
            else:
                fea_code = self.build_fea_from_records(fea_records, ctx['tone_configs'], ctx['is_adv'])
                injected_count = self.inject_fea_to_font(fea_code)

            gdef_line_th = gdef_line_en = ""
            if not do_assign_gdef and not single_scope:
                self.remove_own_gdef_from_prefix()
            if do_assign_gdef and not single_scope:
                classes = self.collect_gdef_classes(raw_glyphs)
                gdef_ok = self.inject_gdef_to_prefix(self.build_gdef_table_code(classes))
                counts = tuple(len(classes.get(c, [])) for c in (OT_CLASS_BASE, OT_CLASS_LIGATURE, OT_CLASS_MARK))
                gdef_line_th = "- table GDEF (Base {} / Ligature {} / Mark {}) ลง Features prefix: {}\n".format(
                    *(counts + ("สำเร็จ" if gdef_ok else "ไม่สำเร็จ",)))
                gdef_line_en = "- table GDEF (Base {} / Ligature {} / Mark {}) in Features prefix: {}\n".format(
                    *(counts + ("Done" if gdef_ok else "Failed",)))
            self.notify_features_changed()

            err_total = self.error_total()
            if not err_total and not single_scope:
                self.lbl_next_step.setText(UI_TEXT[self.lang]['next_step_done'])
            fea_line_th = "" if single_scope else "- เขียน Features (ccmp, mark, mkmk): {} feature\n".format(injected_count)
            fea_line_en = "" if single_scope else "- Features written (ccmp, mark, mkmk): {}\n".format(injected_count)
            features_changed = injected_count > 0 or do_assign_gdef
            next_th = ("- 👉 ขั้นตอนถัดไป: เปิดพาเนล Features แล้วกดปุ่ม ▶ (Compile)" if features_changed and not single_scope
                       else "- 👉 ตรวจ anchor ใน Glyph window (Features ไม่ได้ถูกแก้)")
            next_en = ("- 👉 Next step: Open Features panel and click ▶ (Compile)" if features_changed and not single_scope
                       else "- 👉 Check anchors in the Glyph window (Features unchanged)")

            summary_th = (
                "{} ปักหมุด Anchor: {} / {} glyph สำเร็จ (ล้าง anchor เดิม {} จุด)\n"
                "{}"
                "{}"
                "{}"
            ).format("🎉" if not err_total else "⚠️", success_count, count, ctx['cleared'], gdef_line_th, fea_line_th,
                     next_th if not err_total
                     else "- ❌ พบข้อผิดพลาด {} ครั้ง — ตรวจ log ด้านบน".format(err_total))

            summary_en = (
                "{} Anchors placed: {} / {} glyphs (cleared {} old anchors)\n"
                "{}"
                "{}"
                "{}"
            ).format("🎉" if not err_total else "⚠️", success_count, count, ctx['cleared'], gdef_line_en, fea_line_en,
                     next_en if not err_total
                     else "- ❌ {} errors — see log above".format(err_total))

            self.report(summary_th if self.lang == 'th' else summary_en)

        except Exception as e:
            import traceback
            self.log("เกิดข้อผิดพลาด: {}".format(e) if self.lang == 'th' else "Error occurred: {}".format(e))
            self.log("<pre>{}</pre>".format(html.escape(traceback.format_exc())))
        finally:
            self.btn_stop.setEnabled(False)

    def build_fea_from_records(self, rec, tone_configs, is_adv):
        am = rec.get('sara_am')
        nik = rec.get('nikhahit')
        aa = rec.get('sara_aa')

        bot_vow_names = [g_name for g_name, _, _ in rec.get('bot_vow', [])]
        tall_cons_names = rec.get('tall_cons', [])

        top_vow_names = []
        for item in rec.get('top_vow', []):
            g_name = item[0]
            if '.' not in g_name and g_name not in top_vow_names:
                top_vow_names.append(g_name)

        tones_up_pairs = []
        for key in ('maiEk', 'maiTho', 'maiTri', 'maiChattawa', 'thanthakhat'):
            if key in rec.get('tones', {}):
                base_t_name = rec['tones'][key][0]
                for alt_name, alt_sfx, _, _ in rec.get('tones_alt', {}).get(key, []):
                    if alt_sfx in UPSTAIRS_SUFFIXES:
                        tones_up_pairs.append((base_t_name, alt_name))
                        break

        lines = [
            "# ==========================================",
            "# Auto-Generated by F0NT Autotune v1.0 (ccmp + mark + mkmk)",
            "# ==========================================",
            "feature ccmp {"
        ]

        # 1. จัดการสระอำ (Decomposition & Tone Stacking)
        if am and nik and aa:
            lines.append("    # 1. จัดการสระอำ (Decomposition & Tone Stacking)")
            if tones_up_pairs:
                tones_reg_str = " ".join([b for b, u in tones_up_pairs])
                tones_up_str = " ".join([u for b, u in tones_up_pairs])
                lines.append("    @F0NT_TONES_REG = [{}];".format(tones_reg_str))
                lines.append("    @F0NT_TONES_UP = [{}];".format(tones_up_str))
                lines.append("    # เมื่อพิมพ์ วรรณยุกต์ + สระอำ (ตามแป้นพิมพ์ไทย) ให้สลับวรรณยุกต์เป็นตัวยกชั้น 3 (.up/.small)")
                lines.append("    sub @F0NT_TONES_REG' {} by @F0NT_TONES_UP;".format(am))
                lines.append("    # กรณีพิมพ์กลับลำดับ (สระอำ + วรรณยุกต์)")
                lines.append("    sub {} @F0NT_TONES_REG' by @F0NT_TONES_UP;".format(am))
            lines.append("    # แยกสระอำเป็น นิคหิต + สระอา เพื่อจัดตำแหน่ง Mark ให้ถูกต้อง")
            lines.append("    sub {} by {} {};".format(am, nik, aa))
        elif am:
            lines.append("    # 1. สระอำ ({}): ข้ามการแยกส่วนประกอบ เนื่องจากไม่พบ Glyph นิคหิต (U+0E4D) หรือ สระอา (U+0E32) ในฟอนต์".format(am))

        # 2. กฎตัดเชิง/หาง (ญ, ฐ, ฎ, ฏ)
        desc_bases = rec.get('desc_bases', {})
        desc_less = rec.get('desc_less', {})
        if desc_bases and desc_less and bot_vow_names:
            lines.append("")
            lines.append("    # 2. ตัดเชิง/หาง (ญ, ฐ, ฎ, ฏ) อัตโนมัติเมื่อมีสระอุ/สระอู/พินทุ")
            lines.append("    @F0NT_BOTTOM_MARKS = [{}];".format(" ".join(bot_vow_names)))
            for u, base_name in sorted(desc_bases.items()):
                less_name = desc_less.get(u)
                if less_name:
                    lines.append("    sub {}' @F0NT_BOTTOM_MARKS by {};".format(base_name, less_name))

        # 3. สลับวรรณยุกต์ชั้น 3
        if top_vow_names and tones_up_pairs:
            lines.append("")
            lines.append("    # 3. สลับวรรณยุกต์ชั้น 3 (.small/.up) อัตโนมัติเมื่ออยู่บนสระบน")
            lines.append("    @F0NT_TOP_VOWELS_BASE = [{}];".format(" ".join(top_vow_names)))
            if not (am and nik and aa):
                tones_reg_str = " ".join([b for b, u in tones_up_pairs])
                tones_up_str = " ".join([u for b, u in tones_up_pairs])
                lines.append("    @F0NT_TONES_REG = [{}];".format(tones_reg_str))
                lines.append("    @F0NT_TONES_UP = [{}];".format(tones_up_str))
            lines.append("    sub @F0NT_TOP_VOWELS_BASE @F0NT_TONES_REG' by @F0NT_TONES_UP;")

        # 4. สลับสระบนหลบหาง ป ฝ ฟ ฬ
        top_vow_left = rec.get('top_vow_left', {})
        if tall_cons_names and top_vow_left:
            lines.append("")
            lines.append("    # 4. สลับสระบนหลบหางพยัญชนะ ป ฝ ฟ ฬ")
            lines.append("    @F0NT_TALL_CONS = [{}];".format(" ".join(tall_cons_names)))
            base_vow_map = {}
            for item in rec.get('top_vow', []):
                g_name = item[0]
                u_v, sfx_v = self.resolve_name_to_unicode(g_name)
                if u_v and not sfx_v:
                    base_vow_map[u_v] = g_name
            for u_v, (left_name, _) in sorted(top_vow_left.items()):
                b_name = base_vow_map.get(u_v)
                if b_name and b_name != left_name:
                    lines.append("    sub @F0NT_TALL_CONS {}' by {};".format(b_name, left_name))

        lines.append("} ccmp;")
        lines.append("")

        if not rec['cons']:
            return "\n".join(lines)

        lines.append("feature mark {")
        for item in rec['top_vow']:
            g_name, cx, cy = item[0], item[1], item[2]
            lines.append("    markClass [{}] <anchor {} {}> @F0NT_TOP_VOWELS;".format(g_name, cx, cy))
        for g_name, cx, cy in rec['bot_vow']:
            lines.append("    markClass [{}] <anchor {} {}> @F0NT_BOTTOM_VOWELS;".format(g_name, cx, cy))

        if not is_adv:
            for key, (g_name, cx, cy) in rec['tones'].items():
                lines.append("    markClass [{}] <anchor {} {}> @F0NT_TOP_VOWELS;".format(g_name, cx, cy))

        if rec['top_vow'] or (not is_adv and rec['tones']):
            lines.append("")
            lines.append("    lookup mark_base_top {")
            for g_name, tx, ty, bx, by in rec['cons']:
                lines.append("        pos base [{}] <anchor {} {}> mark @F0NT_TOP_VOWELS;".format(g_name, tx, ty))
            lines.append("    } mark_base_top;")

        if rec['bot_vow']:
            lines.append("")
            lines.append("    lookup mark_base_bottom {")
            for g_name, tx, ty, bx, by in rec['cons']:
                lines.append("        pos base [{}] <anchor {} {}> mark @F0NT_BOTTOM_VOWELS;".format(g_name, bx, by))
            lines.append("    } mark_base_bottom;")

        if is_adv and rec['tones']:
            lines.append("")
            for key, cfg in tone_configs.items():
                if key not in rec['tones']:
                    continue
                t_name, t_cx, t_cy = rec['tones'][key]
                cls_name = "@F0NT_TONE_" + key.upper()
                lkp_name = "mark_tone_" + key
                lines.append("    markClass [{}] <anchor {} {}> {};".format(t_name, t_cx, t_cy, cls_name))
                for alt_name, _, alt_cx, alt_cy in rec.get('tones_alt', {}).get(key, []):
                    lines.append("    markClass [{}] <anchor {} {}> {};".format(alt_name, alt_cx, alt_cy, cls_name))
                lines.append("    lookup {} {{".format(lkp_name))
                for g_name, tx, ty, bx, by in rec['cons']:
                    lines.append("        pos base [{}] <anchor {} {}> mark {};".format(
                        g_name, tx + cfg['offset'], ty, cls_name
                    ))
                lines.append("    }} {};".format(lkp_name))

        lines.append("} mark;")
        lines.append("")

        lines.append("feature mkmk {")
        if rec['top_vow'] and rec['tones']:
            if is_adv:
                for key, cfg in tone_configs.items():
                    if key not in rec['tones']:
                        continue
                    t_name, t_cx, t_cy = rec['tones'][key]
                    cls_name = "@F0NT_MKMK_" + key.upper()
                    lkp_name = "mkmk_tone_" + key
                    lines.append("    markClass [{}] <anchor {} {}> {};".format(t_name, t_cx, t_cy, cls_name))
                    for alt_name, _, alt_cx, alt_cy in rec.get('tones_alt', {}).get(key, []):
                        lines.append("    markClass [{}] <anchor {} {}> {};".format(alt_name, alt_cx, alt_cy, cls_name))
                    lines.append("    lookup {} {{".format(lkp_name))
                    for item in rec['top_vow']:
                        v_name, v_ymax = item[0], item[3]
                        v_cx = item[4] if len(item) > 4 else item[1]
                        lines.append("        pos mark [{}] <anchor {} {}> mark {};".format(
                            v_name, v_cx + cfg['offset'], v_ymax, cls_name
                        ))
                    lines.append("    }} {};".format(lkp_name))
            else:
                for key, (t_name, t_cx, t_cy) in rec['tones'].items():
                    lines.append("    markClass [{}] <anchor {} {}> @F0NT_MKMK_TONES;".format(t_name, t_cx, t_cy))
                lines.append("")
                lines.append("    lookup mkmk_tones_std {")
                for item in rec['top_vow']:
                    v_name, v_ymax = item[0], item[3]
                    v_cx = item[4] if len(item) > 4 else item[1]
                    lines.append("        pos mark [{}] <anchor {} {}> mark @F0NT_MKMK_TONES;".format(v_name, v_cx, v_ymax))
                lines.append("    } mkmk_tones_std;")
        else:
            lines.append("    # No top_vow + tone pairs in current scope")
        lines.append("} mkmk;")

        return "\n".join(lines)

    def get_features(self):
        """fgOTLayout ของฟอนต์ (ข้อมูล Features panel) หรือ None"""
        try:
            return self.fg_font.features
        except Exception as e:
            self.log_error("fgFont.features", e)
            return None

    def split_fea_blocks(self, raw_code):
        """แยกโค้ดเป็น {tag: 'feature tag { ... } tag;'} พร้อมใส่ marker ของ F0NT ในแต่ละบล็อก"""
        blocks = {}
        cur_tag = None
        cur_lines = []
        for line in raw_code.splitlines():
            trimmed = line.strip()
            if cur_tag is None and trimmed.startswith('feature ') and trimmed.endswith('{'):
                parts = trimmed.split()
                if len(parts) >= 2:
                    cur_tag = parts[1]
                    cur_lines = [line, "    # " + FEA_MARKER + " (auto-generated)"]
            elif cur_tag and trimmed == "} " + cur_tag + ";":
                cur_lines.append(line)
                blocks[cur_tag] = "\n".join(cur_lines)
                cur_tag = None
                cur_lines = []
            elif cur_tag:
                cur_lines.append(line)
        return blocks

    def inject_fea_to_font(self, raw_code):
        """เขียน feature ccmp / mark / mkmk ลง Features panel ด้วย fgOTLayout.set_feature()
        feature เดิมที่ไม่ได้สร้างโดย F0NT จะถูกเขียนทับเฉพาะเมื่อเลือกตัวเลือกไว้และยืนยันแล้ว
        คืนจำนวน feature ที่เขียนสำเร็จ"""
        if not raw_code:
            return 0

        # Copy to clipboard silently as safety backup
        try:
            QtGui.QApplication.clipboard().setText(raw_code)
        except Exception:
            pass

        feats = self.get_features()
        if feats is None:
            return 0

        blocks = self.split_fea_blocks(raw_code)
        foreign = []
        for tag in blocks:
            try:
                if feats.has_key(tag) and FEA_MARKER not in (feats.get_feature(tag) or ""):
                    foreign.append(tag)
            except Exception as e:
                self.log_error("get_feature", e, tag)

        if foreign:
            allow = self.is_checked(self.chk_clean_old_fea) and self.confirm_action(
                "Feature {} มีอยู่แล้วในฟอนต์และไม่ได้สร้างโดย F0NT Autotune\nเขียนทับหรือไม่?".format(", ".join(foreign)),
                "Feature {} already exists and was not created by F0NT Autotune.\nOverwrite?".format(", ".join(foreign))
            )
            if not allow:
                self.log("⚠️ ข้าม Feature เดิม: {} (โค้ดใหม่ถูก copy ไว้ใน Clipboard)".format(", ".join(foreign))
                         if self.lang == 'th' else "⚠️ Skipped existing features: {} (new code copied to clipboard)".format(", ".join(foreign)))
                for tag in foreign:
                    del blocks[tag]

        injected_count = 0
        for tag in ('ccmp', 'mark', 'mkmk'):
            if tag not in blocks:
                continue
            if not self.fea_block_has_rules(blocks[tag]):
                # feature ว่างทำให้ Compile ล้มเหลว — ไม่เขียน และลบ feature ว่าง/เก่าของ F0NT ทิ้ง
                self.log("ℹ️ ไม่มีกฎสำหรับ {} ในรอบนี้ — ไม่เขียน feature นี้".format(tag) if self.lang == 'th'
                         else "ℹ️ No rules for {} — feature not written".format(tag))
                self.remove_own_feature(feats, tag)
                continue
            try:
                feats.set_feature(tag, blocks[tag])
                injected_count += 1
            except Exception as e:
                self.log_error("set_feature", e, tag)
        return injected_count

    def fea_block_has_rules(self, block):
        """True ถ้าบล็อก feature มีคำสั่งจริงอย่างน้อย 1 บรรทัด (ไม่นับคอมเมนต์และบรรทัดเปิด/ปิด)"""
        for line in block.splitlines():
            l = line.strip()
            if not l or l.startswith('#') or l.startswith('}'):
                continue
            if l.startswith('feature ') and l.endswith('{'):
                continue
            return True
        return False

    def remove_empty_own_features(self):
        """ลบ feature ccmp / mark / mkmk ของ F0NT ที่ไม่มีกฎ (ค้างจากรอบก่อน ทำให้ Compile ล้มเหลว)"""
        feats = self.get_features()
        if feats is None:
            return
        for tag in ('ccmp', 'mark', 'mkmk'):
            try:
                code = feats.get_feature(tag) if feats.has_key(tag) else ""
            except Exception as e:
                self.log_error("get_feature", e, tag)
                continue
            if code and FEA_MARKER in code and not self.fea_block_has_rules(code):
                self.remove_own_feature(feats, tag)

    def remove_own_feature(self, feats, tag):
        """ลบ feature เฉพาะเมื่อเป็นของ F0NT (มี marker) เท่านั้น"""
        try:
            if feats.has_key(tag) and FEA_MARKER in (feats.get_feature(tag) or ""):
                feats.remove(tag)
                self.log("🗑️ ลบ feature {} เดิมของ F0NT ออก".format(tag) if self.lang == 'th'
                         else "🗑️ Removed previous F0NT feature {}".format(tag))
        except Exception as e:
            self.log_error("features.remove", e, tag)

    def strip_own_gdef(self, prefix):
        """ตัดบล็อก GDEF ของ F0NT (ระหว่าง marker) ออกจากข้อความ prefix — คืน (prefix ใหม่, พบหรือไม่) หรือ (None, False) ถ้า marker ไม่ครบ"""
        start = prefix.find(GDEF_PREFIX_BEGIN)
        if start == -1:
            return prefix, False
        end = prefix.find(GDEF_PREFIX_END, start)
        if end == -1:
            self.log("⚠️ พบ marker GDEF ของ F0NT ไม่ครบใน prefix — ไม่แก้ไข" if self.lang == 'th'
                     else "⚠️ Incomplete F0NT GDEF marker in prefix — not modified")
            return None, False
        return prefix[:start].rstrip("\n") + "\n" + prefix[end + len(GDEF_PREFIX_END):].lstrip("\n"), True

    def remove_own_gdef_from_prefix(self):
        """ลบบล็อก GDEF ที่ F0NT เคยเขียนไว้ใน prefix (ไม่แตะส่วนอื่นของ prefix)"""
        feats = self.get_features()
        if feats is None:
            return
        try:
            prefix, found = self.strip_own_gdef(feats.get_prefix() or "")
            if found and prefix is not None:
                feats.set_prefix(prefix.strip("\n") + "\n")
                self.log("🗑️ ลบ table GDEF เดิมของ F0NT ออกจาก prefix (FontLab สร้าง GDEF จาก OT Class เอง)" if self.lang == 'th'
                         else "🗑️ Removed previous F0NT table GDEF from prefix (FontLab builds GDEF from OT classes)")
        except Exception as e:
            self.log_error("remove GDEF from prefix", e)

    def inject_gdef_to_prefix(self, gdef_code):
        """เขียน table GDEF ลง Features prefix ภายใน marker ของ F0NT (แทนที่บล็อกเดิมของ F0NT เท่านั้น)"""
        if not gdef_code:
            return False
        feats = self.get_features()
        if feats is None:
            return False
        try:
            prefix = feats.get_prefix() or ""
        except Exception as e:
            self.log_error("get_prefix", e)
            return False

        prefix, _ = self.strip_own_gdef(prefix)
        if prefix is None:
            return False

        if "table GDEF" in prefix:
            self.log("⚠️ มี table GDEF อื่นอยู่ใน prefix แล้ว — ไม่เขียนซ้ำ" if self.lang == 'th'
                     else "⚠️ Another table GDEF already exists in prefix — not written")
            return False
        try:
            if feats.has_key('GDEF'):
                self.log("⚠️ พบ feature ชื่อ 'GDEF' (จากสคริปต์รุ่นเก่า) ใน Features panel — ควรลบออกเองก่อน Compile"
                         if self.lang == 'th' else "⚠️ Found a feature named 'GDEF' (legacy script) — remove it manually before compiling")
        except Exception:
            pass

        new_prefix = prefix.strip("\n")
        new_prefix = (new_prefix + "\n\n" if new_prefix else "") + GDEF_PREFIX_BEGIN + "\n" + gdef_code + "\n" + GDEF_PREFIX_END + "\n"
        try:
            feats.set_prefix(new_prefix)
            return True
        except Exception as e:
            self.log_error("set_prefix", e)
            return False

    def notify_features_changed(self):
        try:
            fl6.flItems.notifyPackageContentUpdated(self.fl_pkg.id)
        except Exception as e:
            self.log_error("notifyPackageContentUpdated", e)
        self.update_fontlab_viewport()

    def copy_test_words(self):
        try:
            QtGui.QApplication.clipboard().setText(TEST_WORDS)
            self.lbl_progress_status.setText("คัดลอกคำทดสอบแล้ว — วางใน Preview panel ได้เลย" if self.lang == 'th'
                                             else "Test words copied — paste them into the Preview panel")
        except Exception as e:
            self.log_error("clipboard", e)


# Launch Standalone Panel — ปิดหน้าต่างเดิมก่อน (ตัวแปร global ถูกรีเซ็ตทุกครั้งที่รันสคริปต์ จึงค้นจาก objectName)
for _w in QtGui.QApplication.topLevelWidgets():
    try:
        if _get(_w, 'objectName') == WINDOW_OBJECT_NAME:
            _w.close()
            _w.deleteLater()
    except Exception:
        pass

_f0nt_autotune_instance = F0NTAutotunePanel()
_f0nt_autotune_instance.setObjectName(WINDOW_OBJECT_NAME)
_f0nt_autotune_instance.show()
_f0nt_autotune_instance.raise_()
_f0nt_autotune_instance.activateWindow()

