// 输入法读取词库文件并构建 Trie 树
package com.example.myapplication.data

import android.content.Context
import com.example.myapplication.Trie
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.concurrent.atomic.AtomicBoolean

class WordDictionary(private val context: Context) {

    // 初始化给空 Trie，避免构造期读取导致崩溃
    val wordTrie: Trie = Trie()

    private val loaded = AtomicBoolean(false)

    /** 背景安全加载，多次调用只会生效一次 */
    fun loadIfNeeded() {
        if (!loaded.compareAndSet(false, true)) return
        try {
            context.assets.open("vocab.txt").use { input ->
                BufferedReader(InputStreamReader(input)).useLines { lines ->
                    var idx = 0
                    lines.forEach { line ->
                        idx++
                        if (idx <= 3) return@forEach // 跳过 <unk>, <s>, </s>
                        val w = line.trim()
                        if (w.isNotEmpty()) {
                            wordTrie.insert(w)
                        }
                    }
                }
            }
        } catch (_: Throwable) {
            // 失败也不抛，让输入法继续运行
        }
    }
}