#!/usr/bin/env python3
import json
import os
import subprocess
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
ENV_FILE = Path(os.environ.get("ENV_FILE", ROOT / ".env.paddleocr.verify"))
MAODOU_SETTINGS = Path(os.environ.get("MAODOU_MODEL_SETTINGS", "/Users/alphaPlanet/.maodou/settings/model-settings.json"))

TARGET_MODEL_IDS = ("deepseek-v4-pro", "deepseek-v4-flash", "MiniMax-M2.7")


def load_env(path: Path) -> dict[str, str]:
    values: dict[str, str] = {}
    for raw in path.read_text().splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        values[key.strip()] = value.strip()
    return values


def find_java() -> str:
    configured = os.environ.get("JAVA")
    if configured:
        return configured
    for candidate in (
        "/opt/homebrew/opt/openjdk/bin/java",
        "/usr/bin/java",
        "/Users/alphaPlanet/.vscode/extensions/redhat.java-1.54.0-darwin-arm64/jre/21.0.10-macosx-aarch64/bin/java",
    ):
        if Path(candidate).exists():
            return candidate
    return "java"


def find_jdbc_jar() -> str:
    jars = sorted(Path.home().glob(".m2/repository/com/mysql/mysql-connector-j/*/mysql-connector-j-*.jar"))
    if not jars:
        raise SystemExit("mysql-connector-j jar not found under ~/.m2/repository")
    return str(jars[-1])


def main() -> None:
    env = load_env(ENV_FILE)
    settings = json.loads(MAODOU_SETTINGS.read_text())
    models = settings.get("models", {})
    selected = settings.get("selectedModelId", "deepseek-v4-flash")

    rows = []
    for model_id in TARGET_MODEL_IDS:
        source = models.get(model_id)
        if not source:
            continue
        rows.append({
            "modelId": model_id,
            "provider": "minimax" if model_id.lower().startswith("minimax") else "deepseek",
            "displayName": source.get("displayName") or model_id,
            "baseUrl": source.get("baseUrl") or "",
            "modelName": model_id,
            "apiType": "openai",
            "apiKey": source.get("apiKey") or "",
            "enabled": bool(source.get("enabled", True)),
            "selected": model_id == selected,
            "thinkingEnabled": model_id == "deepseek-v4-pro",
        })

    if not rows:
        raise SystemExit("no matching LLM models found in Maodou settings")

    java_source = """
import java.nio.file.*;
import java.sql.*;
import java.util.*;

public class ImportMaodouLlmSettings {
  public static void main(String[] args) throws Exception {
    String url = System.getenv("SPRING_DATASOURCE_URL");
    String user = System.getenv("SPRING_DATASOURCE_USERNAME");
    String password = System.getenv("SPRING_DATASOURCE_PASSWORD");
    List<String> lines = Files.readAllLines(Path.of(args[0]));
    try (Connection conn = DriverManager.getConnection(url, user, password)) {
      conn.setAutoCommit(false);
      try (Statement st = conn.createStatement()) {
        st.execute("create table if not exists llm_model_config ("
          + "id bigint not null auto_increment, "
          + "model_id varchar(128) not null, "
          + "provider varchar(64) not null, "
          + "display_name varchar(256) not null, "
          + "base_url varchar(512) not null, "
          + "model_name varchar(128) not null, "
          + "api_type varchar(64) not null default 'openai-compatible', "
          + "api_key varchar(512) null, "
          + "enabled tinyint(1) not null default 1, "
          + "selected tinyint(1) not null default 0, "
          + "thinking_enabled tinyint(1) not null default 0, "
          + "created_at datetime(6) not null, "
          + "updated_at datetime(6) not null, "
          + "primary key (id), "
          + "unique key uk_llm_model_config_model_id (model_id), "
          + "key idx_llm_model_config_provider (provider), "
          + "key idx_llm_model_config_selected (selected), "
          + "key idx_llm_model_config_enabled (enabled)"
          + ") engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci");
        st.execute("update llm_model_config set selected = 0");
      }
      String sql = "insert into llm_model_config (model_id, provider, display_name, base_url, model_name, api_type, api_key, enabled, selected, thinking_enabled, created_at, updated_at) "
          + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now(6), now(6)) "
          + "on duplicate key update provider=values(provider), display_name=values(display_name), base_url=values(base_url), model_name=values(model_name), "
          + "api_type=values(api_type), api_key=values(api_key), enabled=values(enabled), selected=values(selected), thinking_enabled=values(thinking_enabled), updated_at=now(6)";
      try (PreparedStatement ps = conn.prepareStatement(sql)) {
        for (String line : lines) {
          String[] row = line.split("\\\\t", -1);
          ps.setString(1, row[0]);
          ps.setString(2, row[1]);
          ps.setString(3, row[2]);
          ps.setString(4, row[3]);
          ps.setString(5, row[4]);
          ps.setString(6, row[5]);
          ps.setString(7, row[6]);
          ps.setBoolean(8, Boolean.parseBoolean(row[7]));
          ps.setBoolean(9, Boolean.parseBoolean(row[8]));
          ps.setBoolean(10, Boolean.parseBoolean(row[9]));
          ps.addBatch();
        }
        ps.executeBatch();
      }
      conn.commit();
    }
    System.out.println("Imported " + lines.size() + " LLM model configs from Maodou settings.");
  }
}
"""

    with tempfile.TemporaryDirectory() as tmp:
        tmp_path = Path(tmp)
        rows_path = tmp_path / "rows.tsv"
        source_path = tmp_path / "ImportMaodouLlmSettings.java"
        rows_path.write_text("\n".join(
            "\t".join(str(row[key]) for key in (
                "modelId",
                "provider",
                "displayName",
                "baseUrl",
                "modelName",
                "apiType",
                "apiKey",
                "enabled",
                "selected",
                "thinkingEnabled",
            ))
            for row in rows
        ) + "\n")
        source_path.write_text(java_source)
        classpath = find_jdbc_jar()
        java = find_java()
        subprocess.run([java.replace("/bin/java", "/bin/javac"), "-cp", classpath, str(source_path)], check=True)
        run_env = os.environ.copy()
        run_env.update({
            "SPRING_DATASOURCE_URL": env["SPRING_DATASOURCE_URL"],
            "SPRING_DATASOURCE_USERNAME": env["SPRING_DATASOURCE_USERNAME"],
            "SPRING_DATASOURCE_PASSWORD": env["SPRING_DATASOURCE_PASSWORD"],
        })
        subprocess.run([java, "-cp", f"{tmp}:{classpath}", "ImportMaodouLlmSettings", str(rows_path)], check=True, env=run_env)


if __name__ == "__main__":
    main()
