from pathlib import Path
from copy import deepcopy
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
R=Path(r'C:\Users\Asus\Desktop\TourAppProject\travelin_app\docs\thesis_appendices')
d=Document(r'C:\Users\Asus\Downloads\256 EDIT 26 (1).docx')
changes={646:'Dart HttpServer (สำหรับพัฒนาระบบหลังบ้าน Backend) และ Node.js กับ npm สำหรับเครื่องมือพัฒนาและ build Web Portal ด้วย Vite',647:'MariaDB (ฐานข้อมูลเชิงสัมพันธ์ที่รองรับ MySQL protocol ใช้ผ่าน XAMPP และเครื่องมือ mysql)',650:'Google Gemini API (สำหรับเรียกวิเคราะห์ข้อความความต้องการ การส่งจับคู่ใช้ข้อมูลแบบฟอร์มและกระบวนการ matching ของระบบ)'}
for i,t in changes.items():
    p=d.paragraphs[i];p.runs[0].text=t
    for r in p.runs[1:]:r.text=''
first=d.paragraphs[757]._p;body=d.element.body;start=body.index(first)
while start>0:
    prev=body[start-1]
    if prev.tag!=qn('w:p') or ''.join(prev.itertext()).strip() or prev.findall('.//'+qn('w:drawing')) or prev.findall('.//'+qn('w:sectPr')):break
    start-=1
for child in list(body)[start:]:
    if child.tag!=qn('w:sectPr'):body.remove(child)
d.core_properties.author='';d.core_properties.last_modified_by=''
d.save(R/'work/merge_base.docx')
a=Document(R/'TourApp_Appendix_A_B.docx')
for name,source,level in [('TourAppAppendixDivider','Title',0),('TourAppAppendixRole','Heading 1',1),('TourAppAppendixTopic','Heading 2',9)]:
    if name not in a.styles:
        el=deepcopy(a.styles[source]._element);el.set(qn('w:styleId'),name)
        el.find(qn('w:name')).set(qn('w:val'),name);a.styles.element.append(el)
    st=a.styles[name];pr=st.element.get_or_add_pPr();ol=pr.find(qn('w:outlineLvl'))
    if ol is None:ol=OxmlElement('w:outlineLvl');pr.append(ol)
    ol.set(qn('w:val'),str(level))
for p in a.paragraphs:
    if p.text in ['ภาคผนวก ก','ภาคผนวก ข']:p.style='TourAppAppendixDivider'
    elif p.style.name=='Heading 1':p.style='TourAppAppendixRole'
    elif p.style.name=='Heading 2':p.style='TourAppAppendixTopic'
for s in a.sections:
    pg=s._sectPr.find(qn('w:pgNumType'))
    if pg is not None and qn('w:start') in pg.attrib:del pg.attrib[qn('w:start')]
a.save(R/'work/appendix_merge_input.docx')
print('MERGE_INPUTS_SAVED_WITH_3_TECHNICAL_CORRECTIONS')
