package com.example.myapplication.service;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class TesseractService {
    private static final String TAG = "TesseractService";
    private static final String TESSDATA_DIR = "tessdata";
    private static final String[] REQUIRED_LANGS = new String[]{"chi_sim.traineddata", "eng.traineddata"};

    public static boolean ensureTessDataInstalled(Context ctx) {
        try {
            File tessDir = new File(ctx.getFilesDir(), TESSDATA_DIR);
            if (!tessDir.exists()) tessDir.mkdirs();
            // 拷贝 assets/tessdata 下的模型到 files/tessdata
            for (String lang : REQUIRED_LANGS) {
                File out = new File(tessDir, lang);
                if (out.exists() && out.length() > 0) continue;
                try (InputStream is = ctx.getAssets().open(TESSDATA_DIR + "/" + lang)) {
                    try (FileOutputStream fos = new FileOutputStream(out)) {
                        byte[] buf = new byte[8192];
                        int r;
                        while ((r = is.read(buf)) > 0) fos.write(buf, 0, r);
                    }
                } catch (Exception e) {
                    Log.w(TAG, "缺少模型文件: " + lang + "，请将其放入 assets/tessdata/", e);
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "安装tessdata失败", e);
            return false;
        }
    }

    public static String recognizeBitmap(Context ctx, Bitmap bmp, String lang, int psm, int oem) {
        if (bmp == null) return "";
        boolean ok = ensureTessDataInstalled(ctx);
        if (!ok) return "";
        String dataPath = ctx.getFilesDir().getAbsolutePath();
        com.googlecode.tesseract.android.TessBaseAPI api = new com.googlecode.tesseract.android.TessBaseAPI();
        try {
            if (!api.init(dataPath, lang)) {
                Log.e(TAG, "Tesseract初始化失败");
                return "";
            }
            try {
                api.setPageSegMode(psm);
            } catch (Throwable ignored) {}
            try {
                api.setVariable("user_defined_dpi", "300");
            } catch (Throwable ignored) {}
            api.setImage(bmp);
            String text = api.getUTF8Text();
            return text == null ? "" : text;
        } catch (Exception e) {
            Log.e(TAG, "Tesseract识别失败", e);
            return "";
        } finally {
            try { api.end(); } catch (Throwable ignored) {}
        }
    }
}