from pathlib import Path
from datetime import datetime
import shutil,json,re
from docx import Document
from docx.shared import Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
R=Path(r'C:\Users\Asus\Desktop\TourAppProject\travelin_app\docs\thesis_appendices')
s=datetime.now().strftime('%Y%m%d_%H%M%S');cp=R/'checkpoints'/('continuation_'+s);cp.mkdir()
d=Document(R/'TourApp_Appendix_A_B.docx')
for p in d.paragraphs:
    if p.text.startswith('[รอภาพหน้าจอจริง: การเตรียมโครงการและแพ็กเกจ]'):
        p.clear();p.alignment=WD_ALIGN_PARAGRAPH.CENTER;p.paragraph_format.first_line_indent=Cm(0);p.paragraph_format.keep_with_next=True
        p.add_run().add_picture(str(R/'screenshots/appendix_a/project_folder_20261003.png'),width=Cm(9))
        cap=p.insert_paragraph_before('ภาพประกอบที่ ก-1 โครงสร้างโฟลเดอร์โครงการ TourApp',style='Caption');p._p.addnext(cap._p)
        cap.alignment=WD_ALIGN_PARAGRAPH.CENTER;cap.paragraph_format.first_line_indent=Cm(0);cap.paragraph_format.keep_with_next=True
        break
else:raise RuntimeError('Project marker missing')
for p in d.paragraphs:
    if p.text=='ภาพประกอบที่ ก-1 การเตรียมและเปิดเว็บ Portal':p.runs[0].text=p.runs[0].text.replace('ก-1','ก-2')
    if p.text.startswith('ใช้ภาพประกอบที่ ก-1 และ ข-1'):
        p.runs[0].text=p.runs[0].text.replace('ก-1','ก-2')
d.save(R/'TourApp_Appendix_A_B.docx');shutil.copy2(R/'TourApp_Appendix_A_B.docx',cp/'02_project_image.docx')
idx=(R/'appendix_image_index.md').read_text(encoding='utf-8').replace('ภาพประกอบที่ ก-1 การเตรียมและเปิดเว็บ Portal','ภาพประกอบที่ ก-2 การเตรียมและเปิดเว็บ Portal').replace('ก-1 และ ข-1','ก-2 และ ข-1')
idx+='\n## ภาพใหม่ในงานต่อเนื่อง\n\n| คำบรรยาย | ไฟล์ | ที่มา | UI จริง หรือ Fixture | ใส่ใน Word | การปกปิดข้อมูล |\n|---|---|---|---|---|---|\n| ภาพประกอบที่ ก-1 โครงสร้างโฟลเดอร์โครงการ TourApp | screenshots/appendix_a/project_folder_20261003.png | work/capture_originals_20261003/project_folder.png จับจาก Windows Explorer ปัจจุบัน | UI จริงใหม่ | แล้ว | ตัด breadcrumb/โฟลเดอร์ส่วนตัวนอกงานออกจากสำเนา ไม่เปลี่ยน UI |\n\nยอดล่าสุด: ภาพแทรกจริง11ตำแหน่งจาก10ไฟล์ (ภาพเดิม10ตำแหน่ง/ภาพใหม่1), ใช้ร่วม5หัวข้อ, Fixture0, marker38จุด เลขภาพ ก-1–ก-2 และ ข-1–ข-9 ต่อเนื่องไม่ซ้ำ\n'
(R/'appendix_image_index.md').write_text(idx,encoding='utf-8')
p=(R/'appendix_pending.md').read_text(encoding='utf-8');p=p.replace('เหลือ 39 หัวข้อ','เหลือ 38 หัวข้อ');p='\n'.join(x for x in p.splitlines() if not x.startswith('| ก.2 '))+'\n';(R/'appendix_pending.md').write_text(p,encoding='utf-8')
with (R/'appendix_progress.md').open('a',encoding='utf-8') as f:f.write('\n## งานต่อเนื่อง '+s+' ชุด 2\n\nใส่ภาพโฟลเดอร์โครงการที่จับใหม่แบบอ่านอย่างเดียวใน ก.2 และปรับเลขภาพ ก ต่อเนื่อง ภาพแทรก11ตำแหน่ง unique10; ภาพใหม่1 ภาพเดิม10ตำแหน่ง shared5 marker38 (B5/C28/D5) ไม่ใช้ภาพสมัครที่ toolbar บังข้อมูล รอเจ้าของเปิด session สำหรับหน้าที่ป้องกันไว้\n')
print('SAVED',s,'PENDING',sum('[รอภาพหน้าจอจริง:' in p.text for p in d.paragraphs),'DRAWINGS',len(d.inline_shapes))
