// 5つの現場の試算（public/sim/service-robot-sites.html）の病院の結果を、ビルドのときに読む。
// 見本の冊子（病院）の数字と図面は、すべてここから出す。試算が正なので、試算を直せば次のビルドで変わる。
// 新しい計算はしない。条件の既定と図面の描き方は、試算のページ（hospital.def・hospBigPlanSvg）と同じ。
import fs from 'node:fs';
import path from 'node:path';

type Row = Record<string, any>;
const html = fs.readFileSync(path.join(process.cwd(), 'public/sim/service-robot-sites.html'), 'utf8');
function readJson(src: string, i: number) {
  let depth = 0, inStr = false, esc = false;
  for (let j = i; j < src.length; j++) {
    const c = src[j];
    if (inStr) { if (esc) esc = false; else if (c === '\\') esc = true; else if (c === '"') inStr = false; continue; }
    if (c === '"') inStr = true;
    else if (c === '{' || c === '[') depth++;
    else if (c === '}' || c === ']') { depth--; if (depth === 0) return JSON.parse(src.slice(i, j + 1)); }
  }
  throw new Error('試算のデータ（const D）が読めません');
}
const D = readJson(html, html.indexOf('const D = ') + 'const D = '.length).hospital;
const K: string[] = D.k;
const ROWS: Row[] = D.r.map((r: any[]) => Object.fromEntries(K.map((k, i) => [k, r[i]])));
export const META = D.meta;

// 試算のページの既定（hospital.def）と、0台のときの決め方（hospital.zero）
export const DEF = { scale: 'mid', robots: 1, demand: 1, floors: 'same', stop_rate: 0.05, dispatch: 'now', busy: 0.6, speed: 0.9 };
const ZERO = { stop_rate: 0, dispatch: 'now', speed: 0.9 };
export function find(c: Partial<typeof DEF>): Row {
  const q: Record<string, any> = { ...DEF, ...c };
  if (q.robots === 0) Object.assign(q, ZERO);
  const r = ROWS.find((row) => Object.keys(DEF).every((k) => row[k] === q[k]));
  if (!r) throw new Error('試算に無い条件です: ' + JSON.stringify(q));
  return r;
}
// 1日の荷物の数（試算のページの hospDaily と同じ）
export const daily = (scale: string, demand: number) => {
  const d = META.demand;
  return (d.r1[demand] * 0.5 + d.r2[demand] * 5.5 + d.r3[demand] * 3) * META.scales[scale].demand_x;
};

// 図面（試算のページの hospPath・hospBigPlanSvg を写したもの）
const ORDER = ['r1', 'r2', 'r3'];
const f = (v: number) => +v.toFixed(2);
function hospPath(p: any, rid: string) {
  const off = ({ r1: -0.9, r2: 0, r3: 0.9 } as any)[rid] * Math.max(0.5, p.w / 150), H = p.d;
  const ps = p.routes[rid].pts, segs: any[] = [];
  for (let i = 0; i < ps.length - 1; i++) segs.push(ps[i][1] === ps[i + 1][1] ? { h: true, c: ps[i][1] + off } : { h: false, c: ps[i][0] + off });
  const out = [ps[0].slice()];
  if (segs[0].h) out[0][1] = segs[0].c; else out[0][0] = segs[0].c;
  for (let i = 1; i < ps.length - 1; i++) { const s0 = segs[i - 1], s1 = segs[i]; out.push(s0.h ? [s1.c, s0.c] : [s0.c, s1.c]); }
  const last = ps[ps.length - 1].slice(), sl = segs[segs.length - 1];
  if (sl.h) last[1] = sl.c; else last[0] = sl.c;
  out.push(last);
  return out.map(([x, y]: number[]) => `${f(x)},${f(H - y)}`).join(' ');
}
export function planSvg(scale: string) {
  const p = META.plans[scale], H = p.d, k = p.w / 25;
  const rect = (a: number[], attrs: string) => `<rect x="${f(a[0])}" y="${f(H - a[3])}" width="${f(a[2] - a[0])}" height="${f(a[3] - a[1])}" ${attrs}/>`;
  const fsz = k * 0.55;
  const label = (a: any[], t: string) => {
    const w = a[2] - a[0], h = a[3] - a[1], cx = f((a[0] + a[2]) / 2), cy = f(H - (a[1] + a[3]) / 2);
    const fs = Math.min(fsz, w / Math.max(t.length, 1) * 0.9, h * 0.5);
    if (fs < k * 0.18) return '';
    return `<text x="${cx}" y="${f(cy + fs * 0.35)}" font-size="${f(fs)}" text-anchor="middle" fill="#333">${t}</text>`;
  };
  const fill: Record<string, string> = { staff: '#e3e3df', core: '#e3e3df', patient: '#ffffff' };
  const ent = ([x0, y0, x1, y1, t]: any[]) => {
    const line = `<line x1="${f(x0)}" y1="${f(H - y0)}" x2="${f(x1)}" y2="${f(H - y1)}" stroke="#f5f5f0" stroke-width="${f(k * 0.4)}"/>`;
    const fs = f(k * 0.5);
    if (y0 === y1) return line + `<text x="${f((x0 + x1) / 2)}" y="${f(H - y0 + (y0 === 0 ? k * 0.8 : -k * 0.4))}" font-size="${fs}" font-weight="600" text-anchor="middle" fill="#111">${t}</text>`;
    const right = x0 >= p.w - 0.01;
    return line + `<text x="${f(right ? x0 + k * 0.3 : x0 - k * 0.3)}" y="${f(H - (y0 + y1) / 2 + k * 0.18)}" font-size="${fs}" font-weight="600" text-anchor="${right ? 'start' : 'end'}" fill="#111">${t}</text>`;
  };
  const leftPad = p.ents.some((e: any) => e[0] === 0 && e[2] === 0) ? k * 3.4 : k * 0.6;
  const rightPad = p.ents.some((e: any) => e[0] >= p.w - 0.01 && e[2] >= p.w - 0.01) ? k * 3.4 : k * 0.6;
  const s = k * 0.26;
  return `<svg viewBox="${f(-leftPad)} ${f(-k * 0.6)} ${f(p.w + leftPad + rightPad)} ${f(H + k * 1.7)}" role="img" aria-label="${p.label}の外来の階の平面図" font-family="Noto Sans JP, sans-serif">`
    + p.buildings.map((a: any) => rect(a, 'fill="#fff"')).join('')
    + p.bridges.map((a: any) => rect(a, `fill="#fff" stroke="#111" stroke-width="${f(k * 0.08)}"`)).join('')
    + p.rooms.map((a: any) => rect(a, `fill="${fill[a[4]]}" stroke="#999" stroke-width="${f(k * 0.05)}"`)).join('')
    + p.rooms.map((a: any) => label(a, a[5])).join('')
    + ORDER.map((r) => `<polyline points="${hospPath(p, r)}" fill="none" stroke="#111" stroke-width="${f(k * 0.16)}" stroke-linejoin="round" stroke-linecap="round"/>`).join('')
    + Object.values(p.stops).map((st: any) => rect([st.at[0] - s, st.at[1] - s, st.at[0] + s, st.at[1] + s], 'fill="#111"')).join('')
    + p.buildings.map((a: any) => rect(a, `fill="none" stroke="#111" stroke-width="${f(k * 0.22)}"`)).join('')
    + p.ents.map(ent).join('')
    + `</svg>`;
}
