/* ===================== OCR overlay — หาพิกัด marker บนแบบจริง =====================
   สถาปัตยกรรม: AI = เนื้อหา(รหัส จาก plan_codes) · CV/OCR = พิกัด (วาง marker) — พอร์ตจาก ocr-poc.html
   API:  window.sbBuildOverlayMarks({ storagePath, pages, codes, onProgress, opts, projectId })
         → { marks: { <pageNum>: [ {code,page,nx,ny,type:'circle'|'text',w?,h?} ] }, stats }
         nx/ny/w/h = สัดส่วนต่อหน้า (0–1) → overlay ใน PdfDrawing คูณขนาด display เอง (ซูมแล้วตรง)
   ‼️ WASM (OpenCV ~10MB / Tesseract) โหลด "ตอนเรียกฟังก์ชันนี้เท่านั้น" (lazy) ไม่โหลดตอนเปิดแอป
   เฟส B = Tesseract-only (ไม่ง้อ provider AI) · เฟส C = เติมขั้นอ่าน montage ด้วย AI (provider ตัดสินภายหลัง) */
(function(){
  const TESS_CDN     = 'https://cdn.jsdelivr.net/npm/tesseract.js@5.1.1/dist/tesseract.min.js';
  const PDFJS_SRC    = 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.min.js';
  const PDFJS_WORKER = 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.worker.min.js';
  // ค่า default ที่จูนมาแล้วจาก POC (อย่าเปลี่ยนถ้าไม่ได้เทสใหม่)
  const D = { scale:3, confMin:45, doVert:true, minR:0.004, maxR:0.012, param2:16, minInk:0.02, cutRight:0.20, maxCircles:250, aiRead:true };
  // เฟส C: อ่านรหัสในวงด้วย Claude ผ่าน Edge Function (action read_montage) — คนละ endpoint กับ analyze ไม่ได้
  const EDGE_URL = 'https://zokzcjbvjcxfjpcjsegx.supabase.co/functions/v1/analyze-drawing';
  const EDGE_PUB = 'sb_publishable_nL-wFMwEzKss2HZOylspIA_9ypFMEWv';
  const AI_CHUNK = 48;   // จำนวนวงต่อ montage (POC ~48)

  const loadScript = (src)=> window.sbLoadScript ? window.sbLoadScript(src) : new Promise((res,rej)=>{
    const el=document.createElement('script'); el.src=src; el.async=true; el.onload=res; el.onerror=()=>rej(new Error('โหลดสคริปต์ไม่ได้: '+src)); document.head.appendChild(el);
  });

  /* ── helpers รหัส ── */
  const norm = t => String(t||'').trim().toUpperCase();
  const isCode = t => /^[A-Z]{1,3}\d{1,3}[A-Z]?$/.test(String(t||'').trim());
  function expandCodes(codes){ const s=new Set();
    (codes||[]).forEach(c=> norm(c).split(/[\s,./|]+/).filter(Boolean).forEach(t=>s.add(t))); return [...s]; }

  /* ── canvas helpers ── */
  function rotateCanvas(src, dir){
    const c=document.createElement('canvas'); c.width=src.height; c.height=src.width;
    const x=c.getContext('2d');
    if(dir==='cw'){ x.translate(c.width,0); x.rotate(Math.PI/2); } else { x.translate(0,c.height); x.rotate(-Math.PI/2); }
    x.drawImage(src,0,0); return c;
  }
  function unrotateBBox(b,W,H,dir){
    return dir==='cw' ? {x0:b.y0,y0:H-b.x1,x1:b.y1,y1:H-b.x0} : {x0:W-b.y1,y0:b.x0,x1:W-b.y0,y1:b.x1};
  }
  async function renderPageCanvas(doc, pageNo, scale){
    const pg = await doc.getPage(pageNo);
    const vp = pg.getViewport({ scale });
    const cv = document.createElement('canvas');
    cv.width = Math.floor(vp.width); cv.height = Math.floor(vp.height);
    await pg.render({ canvasContext: cv.getContext('2d'), viewport: vp }).promise;
    return cv;
  }

  /* ══════════ CV: OpenCV.js Hough ใน Web Worker (WASM ไม่แตะ main thread) ══════════ */
  const CV_WORKER_SRC = `
self.Module = { onRuntimeInitialized(){ self.postMessage({type:'ready'}); } };
try { importScripts('https://docs.opencv.org/4.x/opencv.js'); }
catch(e){ self.postMessage({type:'fail', error:String(e)}); }
self.onmessage = function(e){
  const {id,width,height,data,opt} = e.data;
  try{
    const src = cv.matFromImageData(new ImageData(new Uint8ClampedArray(data), width, height));
    const gray = new cv.Mat();
    cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY);
    cv.medianBlur(gray, gray, 3);
    function pass(p2){
      const c=new cv.Mat();
      cv.HoughCircles(gray, c, cv.HOUGH_GRADIENT, 1, opt.minDist, opt.param1, p2, opt.minR, opt.maxR);
      const a=[]; for(let k=0;k<c.cols;k++) a.push({cx:c.data32F[k*3],cy:c.data32F[k*3+1],r:c.data32F[k*3+2]});
      c.delete(); return a;
    }
    const out = pass(opt.param2);
    for(const m of pass(Math.max(8, opt.param2-6))){
      if(!out.some(a=>Math.hypot(a.cx-m.cx,a.cy-m.cy) < opt.minDist*0.7)) out.push(m);
    }
    src.delete(); gray.delete();
    self.postMessage({type:'circles', id, circles:out});
  }catch(err){ self.postMessage({type:'error', id, error:String(err)}); }
};`;
  let _cvWorker=null, _cvReadyP=null, _cvSeq=0; const _cvPending={};
  function getCvWorker(){
    if(_cvReadyP) return _cvReadyP;
    _cvReadyP = new Promise((resolve,reject)=>{
      let w; try{ w=new Worker(URL.createObjectURL(new Blob([CV_WORKER_SRC],{type:'application/javascript'}))); }
      catch(e){ reject(new Error('สร้าง CV worker ไม่ได้: '+e.message)); return; }
      const to=setTimeout(()=>reject(new Error('OpenCV worker เริ่มต้นนานเกิน 90 วิ')), 90000);
      w.onmessage=(e)=>{ const m=e.data;
        if(m.type==='ready'){ clearTimeout(to); _cvWorker=w; resolve(w); }
        else if(m.type==='fail'){ clearTimeout(to); reject(new Error('โหลด OpenCV.js ใน worker ไม่สำเร็จ: '+m.error)); }
        else if((m.type==='circles'||m.type==='error') && _cvPending[m.id]){ _cvPending[m.id](m.type==='circles'?m.circles:[]); delete _cvPending[m.id]; }
      };
      w.onerror=(e)=>{ clearTimeout(to); reject(new Error('CV worker error: '+(e.message||''))); };
    });
    return _cvReadyP;
  }
  async function detectCirclesWorker(canvas, opt){
    const w = await getCvWorker();
    const img = canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height);
    const minR=Math.max(4,Math.round(canvas.width*opt.minR)), maxR=Math.round(canvas.width*opt.maxR);
    const minDist=Math.max(10,Math.round(canvas.width*0.008));
    return new Promise(resolve=>{
      const id=++_cvSeq; _cvPending[id]=resolve;
      w.postMessage({ id, width:canvas.width, height:canvas.height, data:img.data.buffer,
        opt:{minR,maxR,minDist,param1:100,param2:(opt.param2||16)} }, [img.data.buffer]);
    });
  }

  /* ── กรอง/อ่านวง (Tesseract) ── */
  function circleInkFrac(canvas, cx, cy, r){
    const rr=Math.max(3, Math.round(r*0.72));
    const x0=Math.max(0,Math.round(cx-rr)), y0=Math.max(0,Math.round(cy-rr));
    const w=Math.min(rr*2, canvas.width-x0), h=Math.min(rr*2, canvas.height-y0);
    if(w<4||h<4) return 0;
    const im=canvas.getContext('2d').getImageData(x0,y0,w,h).data;
    const ccx=w/2, ccy=h/2, r2=rr*rr; let ink=0, tot=0;
    for(let y=0;y<h;y++) for(let x=0;x<w;x++){
      if((x-ccx)*(x-ccx)+(y-ccy)*(y-ccy)>r2) continue;
      tot++; const i=(y*w+x)*4;
      if(im[i]*0.3+im[i+1]*0.59+im[i+2]*0.11 < 150) ink++;
    }
    return tot? ink/tot : 0;
  }
  function passesInkGate(canvas, c, minInk){ if(minInk<=0) return true;
    const f=circleInkFrac(canvas, c.cx, c.cy, c.r); return f>=minInk && f<=0.6; }
  function dropOversize(circles, factor){
    if(circles.length<5) return circles;
    const rs=circles.map(c=>c.r).sort((a,b)=>a-b), med=rs[rs.length>>1];
    return circles.filter(c=>c.r <= med*(factor||2.2));
  }
  function dedupeCircles(circles, minD){
    const out=[]; for(const c of circles){ if(!out.some(o=>Math.hypot(o.cx-c.cx,o.cy-c.cy)<minD)) out.push(c); } return out;
  }
  async function ocrCrop(worker, canvas, cx, cy, r, maskR){
    const pad=Math.round(r*1.15), up=4;
    const x0=Math.max(0,Math.round(cx-pad)), y0=Math.max(0,Math.round(cy-pad));
    const s=Math.min(pad*2, canvas.width-x0, canvas.height-y0);
    if(s<6) return '';
    const c=document.createElement('canvas'); c.width=s*up; c.height=s*up;
    const ctx=c.getContext('2d'); ctx.fillStyle='#fff'; ctx.fillRect(0,0,c.width,c.height);
    if(maskR<1.2){ ctx.save(); ctx.beginPath(); ctx.arc(c.width/2,c.height/2, r*maskR*up, 0, 2*Math.PI); ctx.clip(); }
    ctx.drawImage(canvas, x0,y0,s,s, 0,0,c.width,c.height);
    if(maskR<1.2) ctx.restore();
    const im=ctx.getImageData(0,0,c.width,c.height), px=im.data;
    for(let i=0;i<px.length;i+=4){ const v=px[i]*0.3+px[i+1]*0.59+px[i+2]*0.11, b=v<150?0:255; px[i]=px[i+1]=px[i+2]=b; }
    ctx.putImageData(im,0,0);
    return ((await worker.recognize(c)).data.text||'').replace(/[^A-Za-z0-9]/g,'').toUpperCase();
  }
  async function ocrCircle(worker, canvas, cx, cy, r, targets){
    const hit = t => expandCodes([t]).some(c=>targets.includes(c));
    const a = await ocrCrop(worker, canvas, cx, cy, r, 0.85);
    if(hit(a)) return a;
    const b = await ocrCrop(worker, canvas, cx, cy, r, 1.3);
    return hit(b) ? b : a;
  }

  /* ── เฟส C: montage วง → อ่านด้วย Claude ผ่าน Edge Function ── */
  // ต่อ crop วงทั้งหมดเป็นตารางภาพเดียว (แต่ละช่องมีเลขกำกับ) → base64 jpeg
  function buildMontage(canvas, circles){
    const cell=190, cols=8, labelH=24;
    const rows=Math.ceil(circles.length/cols), W=cols*cell, H=rows*(cell+labelH);
    const m=document.createElement('canvas'); m.width=W; m.height=H;
    const ctx=m.getContext('2d'); ctx.fillStyle='#fff'; ctx.fillRect(0,0,W,H);
    ctx.imageSmoothingEnabled=true; ctx.imageSmoothingQuality='high';
    circles.forEach((c,i)=>{
      const col=i%cols, row=(i/cols)|0, x=col*cell, y=row*(cell+labelH);
      ctx.fillStyle='#dc2626'; ctx.font='bold 20px sans-serif'; ctx.textBaseline='top';
      ctx.fillText(String(i+1), x+4, y+1);
      const pad=Math.round(c.r*1.12), sx=Math.max(0,Math.round(c.cx-pad)), sy=Math.max(0,Math.round(c.cy-pad));
      const ss=Math.min(pad*2, canvas.width-sx, canvas.height-sy);
      if(ss>4) ctx.drawImage(canvas, sx,sy,ss,ss, x+3, y+labelH, cell-6, cell-6);
      ctx.strokeStyle='#cbd5e1'; ctx.strokeRect(x, y+labelH, cell, cell);
    });
    return m.toDataURL('image/jpeg',0.95).split(',')[1];
  }
  async function readMontageEdge(b64, count, token, projectId){
    const res = await fetch(EDGE_URL, { method:'POST',
      headers:{ 'Content-Type':'application/json', 'Authorization':'Bearer '+token, 'apikey':EDGE_PUB },
      body: JSON.stringify({ action:'read_montage', image:b64, count, projectId }) });   // projectId: Edge เช็กเจ้าของ + เพดาน (migration 0007)
    if(!res.ok){ let d=''; try{ d=(await res.json()).error||''; }catch(e){} throw new Error('read_montage '+res.status+(d?(' · '+d):'')); }
    const j = await res.json();
    return Array.isArray(j.codes) ? j.codes : [];   // [{n,code}]
  }
  // อ่านวงทั้งหน้าแบบ AI (chunk เป็น montage) → คืน array code text เรียงตรงกับ circles
  async function readCirclesAI(canvas, circles, token, projectId){
    const out = new Array(circles.length).fill('');
    for(let s=0;s<circles.length;s+=AI_CHUNK){
      const grp = circles.slice(s, s+AI_CHUNK);
      const arr = await readMontageEdge(buildMontage(canvas, grp), grp.length, token, projectId);
      arr.forEach(o=>{ const n=Number(o&&o.n); if(n>=1 && n<=grp.length) out[s+n-1]=String((o&&o.code)||''); });
    }
    return out;
  }

  /* ── OCR ป้ายข้อความ 1 หน้า → คืน word bbox ที่แมตช์รหัส ── */
  async function ocrTextPage(worker, cv, codes, opt){
    const runOcr = async c => (await worker.recognize(c)).data;
    const allWords = ((await runOcr(cv)).words||[]).map(w=>({...w}));
    if(opt.doVert){
      const W=cv.width, H=cv.height;
      for(const dir of ['cw','ccw']){
        const dr = await runOcr(rotateCanvas(cv,dir));
        (dr.words||[]).forEach(w=>allWords.push({...w, bbox:unrotateBBox(w.bbox,W,H,dir)}));
      }
    }
    const matchOf = w => { if(w.confidence < opt.confMin) return [];
      const toks = norm(w.text).split(/[\s,./|]+/).filter(Boolean);
      return codes.length ? toks.filter(t=>codes.includes(t)) : toks.filter(isCode); };
    const hits=[];
    for(const w of allWords){ if(!(w.text&&w.text.trim())) continue; const m=matchOf(w); if(m.length) hits.push({w,codes:m}); }
    return hits;
  }

  /* ══════════ main ══════════ */
  async function sbBuildOverlayMarks({ storagePath, pages, codes, onProgress, opts, projectId }){
    const o = Object.assign({}, D, opts||{});
    const prog = (msg,i,total)=>{ try{ onProgress && onProgress({msg,i,total}); }catch(e){} };
    if(!storagePath) throw new Error('ไม่มีไฟล์แบบ (storagePath) สำหรับวาง marker');
    // ‼️ กรอง token สั้น/generic ที่แมตช์เป็น noise ทั่วแบบ: ตัวอักษรเดี่ยว (L,R,C) + เลขล้วน (มิติ 8,10,12)
    //    เก็บรหัสจริงอย่าง WC/CO/FD (2 ตัว) + B2/S1/CW-1/FL-BATH2 (alphanumeric)
    const codeSet = expandCodes(codes).filter(c => c.length >= 2 && !/^\d+$/.test(c));
    if(!codeSet.length) throw new Error('ไม่มีรหัสที่วาง marker ได้ (หลังกรองรหัสสั้น/generic) — รหัสในหน้านี้อาจสั้นเกิน');

    // 1) เปิดเอกสาร PDF (signed URL → pdf.js) — ไฟล์เดียวกับ viewer → index หน้าตรงกัน
    prog('ขอลิงก์ไฟล์แบบ…');
    if(!window.fetchSignedUrl) throw new Error('ยังโหลดตัวช่วยแบบไม่ครบ (fetchSignedUrl)');
    const url = await window.fetchSignedUrl(storagePath);
    if(!window.pdfjsLib) await loadScript(PDFJS_SRC);
    if(!window.pdfjsLib) throw new Error('โหลดตัวอ่าน PDF (pdf.js) ไม่ได้');
    window.pdfjsLib.GlobalWorkerOptions.workerSrc = PDFJS_WORKER;
    const doc = await window.pdfjsLib.getDocument({ url, isEvalSupported: false }).promise; // isEvalSupported:false = ปิดช่องโหว่ CVE-2024-4367 ของ pdf.js 3.x (ฟอนต์ใน PDF สั่งรันโค้ดได้)

    const pageList = (pages && pages.length ? pages : Array.from({length:doc.numPages},(_,i)=>i+1))
      .filter(p=>p>=1 && p<=doc.numPages);

    // 2) โหลด Tesseract (lazy) + สร้าง worker 2 ตัว: ป้ายข้อความ (PSM 11) / ในวง (PSM 8)
    prog('โหลด Tesseract (ครั้งแรกสักครู่)…');
    if(!window.Tesseract) await loadScript(TESS_CDN);
    if(!window.Tesseract) throw new Error('โหลด Tesseract ไม่ได้');
    const wText = await window.Tesseract.createWorker('eng');
    await wText.setParameters({ tessedit_char_whitelist:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-,.', tessedit_pageseg_mode:'11' });
    const wCirc = await window.Tesseract.createWorker('eng');
    await wCirc.setParameters({ tessedit_char_whitelist:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', tessedit_pageseg_mode:'8' });

    // เตรียม CV worker ล่วงหน้า (โหลด OpenCV ~10MB) — ถ้าล้มยังทำ text-only ต่อได้
    let cvOk = true;
    prog('โหลด OpenCV (~10MB ครั้งแรก)…');
    try{ await getCvWorker(); }catch(e){ cvOk=false; console.warn('CV worker load failed → text-only:', e.message); }

    const aiToken = (o.aiRead && opts && opts.accessToken) ? opts.accessToken : null;   // เฟส C: อ่านวงด้วย Claude
    let aiUsed=false, aiFail=false;
    const marks = {}; let circlesTotal=0, textHits=0, circHits=0;
    try{
      for(let i=0;i<pageList.length;i++){
        const pageNo = pageList[i];
        prog(`หน้า ${pageNo} (${i+1}/${pageList.length}) — เรนเดอร์…`, i, pageList.length);
        const cv = await renderPageCanvas(doc, pageNo, o.scale);
        const W=cv.width, H=cv.height, minDist=W/45;
        const pageMarks=[]; const placed={};   // key=code → [{cx,cy}] กันวางซ้ำจุดเดิม
        const addMark = (code, cx, cy, mk) => {
          if((placed[code]||[]).some(p=>Math.hypot(p.cx-cx,p.cy-cy)<minDist)) return false;
          (placed[code]=placed[code]||[]).push({cx,cy}); pageMarks.push(mk); return true;
        };

        // 2a) ป้ายข้อความ (B-codes/F6,C1…) — Tesseract word bbox แมตช์รหัส (closed-set = แม่น)
        prog(`หน้า ${pageNo} (${i+1}/${pageList.length}) — อ่านป้ายข้อความ…`, i, pageList.length);
        try{
          const hits = await ocrTextPage(wText, cv, codeSet, o);
          for(const h of hits){ const b=h.w.bbox; const cx=(b.x0+b.x1)/2, cy=(b.y0+b.y1)/2;
            for(const code of h.codes){
              if(addMark(code, cx, cy, { code, page:pageNo, type:'text',
                nx:b.x0/W, ny:b.y0/H, w:(b.x1-b.x0)/W, h:(b.y1-b.y0)/H })) textHits++;
            }
          }
        }catch(e){ console.warn('text OCR page',pageNo,e.message); }

        // 2b) วงกลม (S1/S2/SP บนพื้น) — CV Hough → ink-gate/dedupe/dropOversize → Tesseract ในวง
        if(cvOk){
          let circles=[]; try{ circles=await detectCirclesWorker(cv, o); }catch(e){}
          if(o.cutRight>0){ const xMax=W*(1-o.cutRight); circles=circles.filter(c=>c.cx<=xMax); }
          circlesTotal += circles.length;
          circles=dedupeCircles(circles, W/45);
          circles=circles.filter(c=>passesInkGate(cv, c, o.minInk));
          circles=dropOversize(circles);
          const forOcr = circles.slice(0, o.maxCircles);
          // อ่านรหัสในวง — AI montage (แม่นสุด) ก่อน · ล้ม/ไม่มี token → Tesseract ในวง (เฟส B)
          let reads = null;
          if(aiToken && forOcr.length){
            prog(`หน้า ${pageNo} (${i+1}/${pageList.length}) — AI อ่านวง ${forOcr.length} จุด…`, i, pageList.length);
            try{ reads = await readCirclesAI(cv, forOcr, aiToken, projectId || (opts && opts.projectId)); aiUsed=true; }
            catch(e){ console.warn('AI montage read ล้ม → Tesseract:', e.message); aiFail=true; reads=null; }
          }
          for(let j=0;j<forOcr.length;j++){
            if(!reads && j%10===0) prog(`หน้า ${pageNo} (${i+1}/${pageList.length}) — อ่านวง ${j+1}/${forOcr.length}…`, i, pageList.length);
            const {cx,cy,r}=forOcr[j];
            const txt = reads ? reads[j] : await ocrCircle(wCirc, cv, cx, cy, r, codeSet);
            const subs = expandCodes([txt]).filter(c=>codeSet.includes(c));
            if(!subs.length) continue;
            const code = subs.join(',');
            if(addMark(code, cx, cy, { code, page:pageNo, type:'circle', nx:cx/W, ny:cy/H })) circHits++;
          }
        }

        if(pageMarks.length) marks[pageNo] = pageMarks;
      }
    } finally {
      try{ await wText.terminate(); }catch(e){}
      try{ await wCirc.terminate(); }catch(e){}
      try{ doc.destroy && doc.destroy(); }catch(e){}
    }

    const foundCodes = new Set(); Object.values(marks).forEach(a=>a.forEach(m=>String(m.code).split(',').forEach(c=>foundCodes.add(c))));
    return { marks, stats:{ pages:pageList.length, circlesTotal, textHits, circHits,
      codesTarget: codeSet.length, codesFound: foundCodes.size, cvOk, aiUsed, aiFail } };
  }

  window.sbBuildOverlayMarks = sbBuildOverlayMarks;
})();
