const roles = {
  ground_line: "断面地形线/河床线",
  water_level: "计算水位线",
  design_water_level: "设计洪水位线",
  backwater_line: "壅水线",
  scour_line: "冲刷线",
  bridge_outline: "桥梁/水工建筑物轮廓",
  pier: "桥墩/墩台",
  station_axis: "桩号/断面轴线",
  label: "文字标注",
  table: "成果表格",
};

let currentMode = "smart";
let lastLayers = [];
let lastGuesses = [];
let lastCadFile = "";
let lastProfilePreview = null;

function api() {
  return window.pywebview && window.pywebview.api ? window.pywebview.api : null;
}

function readLayers() {
  return document.getElementById("layerText").value
    .split(/\n|,|，|;|；/)
    .map((item) => item.trim())
    .filter(Boolean);
}

function escapeHtml(value) {
  return String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function setMessage(id, text, ok = true) {
  const node = document.getElementById(id);
  node.textContent = text;
  node.style.borderLeftColor = ok ? "#1565c0" : "#dc2626";
}

function renderRows(guesses) {
  const root = document.getElementById("mappingTable");
  if (!guesses.length) {
    root.innerHTML = '<div class="notice">没有读取到图层。请先选择本地 DXF 文件，或粘贴图层名称。</div>';
    return;
  }
  root.innerHTML = guesses.map((guess) => `
    <div class="mapping-row">
      <b>${escapeHtml(guess.layer)}</b>
      <span>${escapeHtml(guess.role_label)}${guess.reason ? " · " + escapeHtml(guess.reason) : ""}</span>
      <em class="confidence">${Math.round((guess.confidence || 0) * 100)}%</em>
    </div>
  `).join("");
}

function renderManualSelects() {
  const root = document.getElementById("manualGrid");
  const options = ['<option value="">不指定</option>'].concat(
    lastLayers.map((layer) => `<option value="${escapeHtml(layer)}">${escapeHtml(layer)}</option>`)
  ).join("");
  root.innerHTML = Object.entries(roles).map(([role, label]) => {
    const guessed = lastGuesses.find((item) => item.role === role);
    return `
      <div class="manual-field">
        <label for="role-${role}">${label}${role === "ground_line" ? "（必选）" : ""}</label>
        <select id="role-${role}" data-role="${role}">
          ${options}
        </select>
      </div>
    `;
  }).join("");
  Object.entries(roles).forEach(([role]) => {
    const guessed = lastGuesses.find((item) => item.role === role && item.layer);
    const select = document.getElementById(`role-${role}`);
    if (guessed && select) select.value = guessed.layer;
  });
}

function applyAnalysisResult(result, source = "layers") {
  if (Array.isArray(result.layers)) {
    lastLayers = result.layers;
    document.getElementById("layerText").value = lastLayers.join("\n");
  }
  lastGuesses = result.guesses || [];
  lastProfilePreview = result.profile_preview || null;
  renderRows(lastGuesses);
  renderManualSelects();
  const message = result.message || "识别完成。";
  setMessage(source === "file" ? "fileMessage" : "analysisMessage", message, result.ok !== false);
  if (source === "file") {
    setMessage("analysisMessage", "已从本地文件读取图层，右侧映射已自动填入；低置信度项可手动修正。", true);
  }
}

async function analyze() {
  lastLayers = readLayers();
  const fallback = {
    ok: true,
    guesses: lastLayers.map((layer) => ({ layer, role: "unknown", role_label: "待人工确认", confidence: 0, reason: "浏览器预览模式" })),
    message: "浏览器预览模式：请在软件内使用以调用 Python 识别接口。",
  };
  const result = api()
    ? await window.pywebview.api.analyze_section_cad_layers(lastLayers, currentMode)
    : fallback;
  applyAnalysisResult(result, "layers");
}

async function chooseLocalCadFile() {
  if (!api() || typeof api().select_section_cad_file !== "function") {
    setMessage("fileMessage", "当前未连接本地文件选择接口，请直接粘贴 DXF 文件路径。", false);
    return;
  }
  const button = document.getElementById("chooseFileBtn");
  const previousText = button ? button.textContent : "";
  if (button) {
    button.disabled = true;
    button.textContent = "正在打开...";
  }
  let selected = null;
  try {
    selected = await api().select_section_cad_file();
  } catch (error) {
    setMessage("fileMessage", `打开本地文件选择器失败：${error && error.message ? error.message : error}`, false);
    return;
  } finally {
    if (button) {
      button.disabled = false;
      button.textContent = previousText || "选择本地 CAD/DXF 文件";
    }
  }
  if (!selected || selected.ok === false) {
    setMessage("fileMessage", selected && selected.message ? selected.message : "未选择文件。", false);
    return;
  }
  lastCadFile = selected.path || "";
  document.getElementById("cadFilePath").value = lastCadFile;
  await analyzeLocalCadFile();
}

async function analyzeLocalCadFile() {
  sessionStorage.removeItem('htzd-reviewed-cad-section');
  const path = document.getElementById("cadFilePath").value.trim();
  if (!path) {
    setMessage("fileMessage", "请先选择或粘贴本地 DXF 文件路径。", false);
    return;
  }
  lastCadFile = path;
  const fallback = {
    ok: false,
    message: "浏览器预览模式无法读取本地 CAD/DXF 文件，请从软件内打开。",
  };
  const result = api() && typeof api().analyze_section_cad_file === "function"
    ? await api().analyze_section_cad_file(path, currentMode)
    : fallback;
  if (result.ok === false) {
    setMessage("fileMessage", result.message || "读取本地文件失败。", false);
    return;
  }
  applyAnalysisResult(result, "file");
}

async function validateMapping() {
  const mapping = {};
  document.querySelectorAll("#manualGrid select").forEach((select) => {
    if (select.value) mapping[select.dataset.role] = select.value;
  });
  const fallback = { ok: false, message: "浏览器预览模式无法校核映射。" };
  const result = api()
    ? await window.pywebview.api.validate_section_cad_mapping(lastLayers, mapping)
    : fallback;
  if (result.ok !== false && lastCadFile && api() && typeof api().import_section_cad_profile === "function") {
    const imported = await api().import_section_cad_profile(lastCadFile, mapping);
    if (imported && imported.ok) {
      sessionStorage.setItem('htzd-reviewed-cad-section', JSON.stringify({file:lastCadFile, groundLayer:mapping.ground_line, profile:imported.profile}));
      result.message = `${result.message || "已完成校核。"} 已从断面地形线提取 ${imported.profile.length} 个点。`;
    } else if (imported && imported.message) {
      result.ok = false;
      sessionStorage.removeItem('htzd-reviewed-cad-section');
      result.message = `${result.message || "已完成校核。"} ${imported.message}`;
    }
  }
  setMessage("validateMessage", result.message || "已完成校核。", result.ok !== false);
  if (result.errors && result.errors.length) {
    setMessage("validateMessage", result.errors.join("；"), false);
  }
}

document.querySelectorAll(".mode").forEach((button) => {
  button.addEventListener("click", () => {
    currentMode = button.dataset.mode;
    document.querySelectorAll(".mode").forEach((item) => item.classList.toggle("is-active", item === button));
    analyze();
  });
});

document.getElementById("analyzeBtn").addEventListener("click", analyze);
document.getElementById("chooseFileBtn").addEventListener("click", chooseLocalCadFile);
document.getElementById("analyzeFileBtn").addEventListener("click", analyzeLocalCadFile);
document.getElementById("validateBtn").addEventListener("click", validateMapping);
document.getElementById('cadFilePath').addEventListener('input', () => sessionStorage.removeItem('htzd-reviewed-cad-section'));
document.getElementById('manualGrid').addEventListener('change', () => sessionStorage.removeItem('htzd-reviewed-cad-section'));
document.querySelector('[data-use-section]').addEventListener('click', event => {
  if (!sessionStorage.getItem('htzd-reviewed-cad-section')) {
    event.preventDefault();
    setMessage('validateMessage', '请先选取地形图层并确认映射，取得真实断面点。', false);
  }
});
document.getElementById("loadTemplateBtn").addEventListener("click", () => {
  document.getElementById("layerText").value = [
    "HTZD_SECTION_GROUND",
    "HTZD_SECTION_WATER_LEVEL",
    "HTZD_SECTION_DESIGN_WL",
    "HTZD_SECTION_BACKWATER",
    "HTZD_SECTION_SCOUR",
    "HTZD_STRUCTURE_OUTLINE",
    "HTZD_STRUCTURE_PIER",
    "HTZD_SECTION_AXIS",
    "HTZD_TEXT_LABEL",
    "HTZD_RESULT_TABLE",
  ].join("\n");
  currentMode = "standard";
  document.querySelectorAll(".mode").forEach((item) => item.classList.toggle("is-active", item.dataset.mode === "standard"));
  analyze();
});

analyze();
