df_captions = {} -- bimap: DF ID <> DF caption text
dfhack_captions = {} -- bimap: DFHack ID <> DF caption text
hover_instruction = df.global.game.main_interface.hover_instruction

function xmlescape(s)
    return s:gsub("'", '&apos;'):gsub('<', '&lt;'):gsub('>', '&gt;')
end

for i, lines in ipairs(hover_instruction) do
    local text = ''
    for _, line in ipairs(lines) do
        text = text .. ' ' .. line.value
    end
    text = text:trim():gsub('%s+', ' ')
    df_captions[i] = text
    df_captions[text] = i
end

for i in ipairs(df.main_hover_instruction) do
    local text = df.main_hover_instruction.attrs[i].caption
    dfhack_captions[i] = text
    dfhack_captions[text] = i
end

print("    <enum-type type-name='main_hover_instruction'>")
print("        <comment>generated by devel/dump-tooltip-ids</comment>")
print("        <enum-attr name='caption'/>")
print("")
for i in ipairs(hover_instruction) do
    if i % 10 == 0 then
        print("        " .. i)
    end
    local dfhack_name = nil
    if dfhack_captions[df_captions[i]] then
        -- known caption, use the enum item name that DFHack has for it
        dfhack_name = df.main_hover_instruction[dfhack_captions[df_captions[i]]]
    end

    print(("        <enum-item%s>"):format(dfhack_name and (" name='%s'"):format(xmlescape(dfhack_name)) or ''))
    print(("            <item-attr name='caption' value='%s'/>"):format(xmlescape(df_captions[i])))
    print("        </enum-item>")
end
print("    </enum-type>")

for k, id in pairs(dfhack_captions) do
    if type(k) == 'string' and not df_captions[k] then
        dfhack.printerr(('Unmatched caption: %s: was ID %d, key %s'):format(k, id, df.main_hover_instruction[id]))
    end
end
