"""Insert a frozen-data status slide into the existing six-page presentation."""
from collections import Counter
import json
from pathlib import Path
import shutil
import sys
import zipfile

PROJECT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(PROJECT/'scripts'))
import build_pallet_paper_status_ppt as design
from PIL import Image,ImageDraw
from pptx import Presentation
from pptx.util import Inches,Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import MSO_ANCHOR
from pptx.enum.shapes import MSO_SHAPE_TYPE
from pptx.oxml.xmlchemy import OxmlElement

BASE=PROJECT/'outputs/pallet_paper_status_ppt_20261115_v2'
OUT=PROJECT/'outputs/pallet_paper_status_ppt_20261115_v4'
DATA=design.DATA


def charts(counts):
    # All forty fine classes, sorted by target count. The axis starts at zero.
    im=design.panel('40细类目标数量分布',700,510);d=ImageDraw.Draw(im)
    ordered=sorted(counts['class_counts'].items(),key=lambda kv:(-kv[1],int(kv[0])))
    left,right,top,bottom=55,675,110,370
    for tick in (0,200,400,600,800):
        y=bottom-tick/800*(bottom-top);d.line((left,y,right,y),fill=design.LINE,width=1)
        d.text((left-8,y),str(tick),font=design.font(17),fill=design.MUTED,anchor='rm')
    pitch=(right-left)/len(ordered)
    for i,(cls,n) in enumerate(ordered):
        x=left+i*pitch;y=bottom-n/800*(bottom-top)
        d.rectangle((x+2,y,x+pitch-2,bottom),fill=design.RED if n<20 else design.TEAL)
        label=Image.new('RGBA',(65,22),(0,0,0,0));ld=ImageDraw.Draw(label)
        ld.text((2,0),str(cls),font=design.font(18),fill=design.MUTED,anchor='lt')
        label=label.rotate(90,expand=True);im.paste(label,(round(x+(pitch-22)/2),376),label)
    design.text(im,(25,451),'类别ID按数量降序排列；红色为不足20项的细类',20,design.MUTED)
    design.text(im,(25,480),f"最大类800项，最小类2项；{sum(n<20 for _,n in ordered)}个细类不足20项",19,design.RED)
    result=[design.save_asset(im,'dataset_class_distribution')]

    im=design.panel('训练／组件留出划分',370,510);d=ImageDraw.Draw(im)
    train=counts['splits']['train'];held=counts['splits']['holdout'];total=counts['targets'];angle=360*train/total
    ring=(70,96,300,326);d.pieslice(ring,-90,-90+angle,fill=design.TEAL);d.pieslice(ring,-90+angle,270,fill=design.BLUE)
    d.ellipse((105,131,265,291),fill=design.PALE)
    d.text((185,195),f'{total:,}',font=design.font(36),fill=design.INK,anchor='mm');d.text((185,235),'目标',font=design.font(23),fill=design.MUTED,anchor='mm')
    for y,label,n,color in ((353,'训练',train,design.TEAL),(399,'留出',held,design.BLUE)):
        d.rounded_rectangle((25,y+2,41,y+18),radius=4,fill=color)
        design.text(im,(52,y),f'{label} {n:,}  /  {100*n/total:.1f}%',22,design.INK)
    design.text(im,(25,453),'同图与关联组件不跨集合',21,design.MUTED)
    design.text(im,(25,483),'反复迭代留出，非新盲测',19,design.MUTED)
    result.append(design.save_asset(im,'dataset_split'))

    im=design.panel('标注／监督覆盖',370,510);d=ImageDraw.Draw(im)
    for i,(label,n) in enumerate((('类别／轮廓可用',total),('具有语义监督',counts['semantic']),('观察文字监督',counts['observation']))):
        y=106+i*104;design.text(im,(25,y),label,23)
        d.text((343,y),f'{n:,}',font=design.font(25),fill=design.TEAL,anchor='rt')
        d.rounded_rectangle((25,y+44,345,y+64),radius=9,fill=design.LINE)
        d.rounded_rectangle((25,y+44,25+320*n/total,y+64),radius=9,fill=design.TEAL if i<2 else design.BLUE)
        design.text(im,(25,y+73),f'{100*n/total:.1f}%  /  全部目标',17,design.MUTED)
    design.text(im,(25,445),'覆盖项相互重叠，不可相加',20,design.MUTED)
    design.text(im,(25,479),'无备注 ≠ 正常负样本',20,design.RED)
    result.append(design.save_asset(im,'dataset_supervision'))
    return result


def native_text(slide,x,y,w,h,lines,size,color):
    sh=slide.shapes.add_textbox(Inches(x/120),Inches(y/120),Inches(w/120),Inches(h/120));tf=sh.text_frame
    tf.margin_left=tf.margin_right=tf.margin_top=tf.margin_bottom=0;tf.word_wrap=False;tf.vertical_anchor=MSO_ANCHOR.TOP
    p=tf.paragraphs[0];p.line_spacing=Pt(size*1.42*72/120);p.space_before=p.space_after=Pt(0)
    for i,line in enumerate(lines):
        if i:p.add_line_break()
        r=p.add_run();r.text=line;r.font.name='Noto Sans CJK SC';r.font.size=Pt(size*72/120);r.font.color.rgb=RGBColor.from_string(color.lstrip('#'))
        ea=OxmlElement('a:ea');ea.set('typeface','Noto Sans CJK SC');r._r.get_or_add_rPr().append(ea)


def signature(slide):
    return [(int(sh.shape_type),sh.left,sh.top,sh.width,sh.height,sh.text if sh.has_text_frame else None,sh.image.sha1 if sh.shape_type==MSO_SHAPE_TYPE.PICTURE else None) for sh in slide.shapes]


def build():
    assert not OUT.exists(),'Preserve existing artifact versions'
    training=design.rows(DATA/'private/training.jsonl');sem=design.rows(DATA/'description_data/records.jsonl');report=design.read(DATA/'preparation_report.json')
    assert {r['target_key'] for r in training}=={r['target_key'] for r in sem}
    counts=dict(targets=len(training),images=len({r['image_sha256'] for r in training}),fine_classes=len({r['class_id'] for r in training}),parents=len({r['parent'] for r in training}),
        splits=dict(Counter(r['evaluation_branch_split'] for r in training)),class_counts=dict(Counter(r['class_id'] for r in training)),semantic=sum(any(r['supervised_fields'].values()) for r in sem),
        observation=sum(bool(r['supervised_fields']['观察']) for r in sem),historical_actions=dict(Counter(r['original_review_action'] for r in training)))
    assert (counts['targets'],counts['images'],counts['fine_classes'],counts['parents'],counts['semantic'],counts['observation'])==(8698,8659,40,9,8425,1039)
    assert counts['targets']==report['targets'] and counts['splits']==report['splits'] and counts['observation']==report['semantic_supervised_fields']['观察']
    assert {str(k):v for k,v in counts['class_counts'].items()}==report['training_class_counts']
    assert counts['splits']=={'train':6679,'holdout':2019}
    # Counts do not promote inherited draft/never_saved source actions to correct.
    original=BASE/'托盘识别与VLM_论文工作现状_6页.pptx';oldhash=design.sha(original)
    OUT.mkdir();shutil.copytree(BASE/'assets',OUT/'assets');shutil.copytree(BASE/'字体',OUT/'字体');(OUT/'previews').mkdir()
    design.OUT=OUT;figures=charts(counts)
    title='数据集现状：规模、分布与标注覆盖'
    lines=['第八轮冻结集包含8,659张原图、8,698个目标，覆盖40细类、9大类。',
           '训练／组件留出为6,679／2,019项；语义监督覆盖8,425项，其中1,039项有观察文字监督。',
           '类别分布呈长尾，缺少备注不等于正常负样本。']
    paragraph=''.join(lines)
    assert len(lines)<=3 and all(design.font(30).getlength(line)<1480 for line in lines) and design.font(49).getlength(title)<1480
    prs=Presentation(original);prior_signatures=[signature(s) for s in prs.slides];slide=prs.slides.add_slide(prs.slide_layouts[6])
    native_text(slide,60,52,1480,78,[title],49,design.INK);native_text(slide,60,144,1480,145,lines,30,design.MUTED)
    preview=Image.new('RGB',(1600,900),'white');design.text(preview,(60,57),title,49);design.text(preview,(60,151),'\n'.join(lines),30,design.MUTED,spacing=1.42)
    boxes=[(60,320,700,510),(780,320,370,510),(1170,320,370,510)]
    for path,(x,y,w,h) in zip(figures,boxes):
        slide.shapes.add_picture(str(path),Inches(x/120),Inches(y/120),width=Inches(w/120),height=Inches(h/120));preview.paste(Image.open(path),(x,y))
    sources=[DATA/'preparation_report.json',DATA/'private/training.jsonl',DATA/'description_data/records.jsonl']
    slide.notes_slide.notes_text_frame.text='第3页｜第八轮冻结数据口径，非在线动态进度。\n'+'\n'.join(str(p.relative_to(PROJECT)) for p in sources)+'\n40细类分布逐目标重算；语义监督指至少一个supervised_fields为真；观察为其中观察字段有监督的子集，不是独立异常类别统计。\n类别／轮廓可用指已纳入本研究冻结集且有几何记录，不等于8,698项均为最新单图correct或正式GT；原接受基线的历史draft/never_saved状态不改写。\n三条监督覆盖非互斥集合，不可求和；无备注不能充当正常负样本。训练/留出按关联组件划分，不是新盲测。'
    slideids=prs.slides._sldIdLst;newid=slideids[-1];slideids.remove(newid);slideids.insert(2,newid)
    prs.core_properties.subject='7页工作现状；第3页新增冻结数据规模、40细类分布、划分与监督覆盖'
    ppt=OUT/'托盘识别与VLM_论文工作现状_7页.pptx';prs.save(ppt)
    previews=[]
    for i in range(7):
        if i==2:im=preview
        else:
            old_index=i if i<2 else i-1
            im=Image.open(BASE/'previews'/f'slide_{old_index+1:02d}.png').convert('RGB')
        im.save(OUT/'previews'/f'slide_{i+1:02d}.png');previews.append(im)
    previews[0].save(OUT/'托盘识别与VLM_论文工作现状_预览.pdf',save_all=True,append_images=previews[1:],resolution=120)
    contact=Image.new('RGB',(1640,1930),'#E6ECF0')
    for i,im in enumerate(previews):contact.paste(im.resize((800,450),Image.Resampling.LANCZOS),(10+(i%2)*820,10+(i//2)*480))
    contact.save(OUT/'七页总览.png')
    manifest=design.read(BASE/'sources.json');manifest['slides'].insert(2,dict(page=3,title=title,paragraph=paragraph,figures=[p.stem for p in figures],sources=[str(p.relative_to(PROJECT)) for p in sources],layout='title + one paragraph + three charts',preview_kind='same-layout Pillow rendering, not Office screenshot'))
    for i,s in enumerate(manifest['slides']):s['page']=i+1
    manifest['assets'].extend(dict(path=str(p.relative_to(PROJECT)),sha256=design.sha(p),usage='新增数据集现状页统计来源') for p in sources)
    (OUT/'sources.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2));(OUT/'dataset_counts.json').write_text(json.dumps(counts,ensure_ascii=False,indent=2))
    (OUT/'说明.txt').write_text('七页版：第3页新增“数据集现状”，原六页内容与配图保持。\n每页仅标题、一段短文和2–3张图；PPT标题与正文可编辑。\n统计采用第八轮冻结口径，非实时在线进度；来源及统计定义在备注、sources.json与dataset_counts.json。\n字体Noto Sans CJK SC在字体目录；PDF/PNG为同版式直接生成的预览，不是Office截图。\n')
    check=Presentation(ppt);assert len(check.slides)==7
    for old_i,new_i in enumerate((0,1,3,4,5,6)):assert signature(check.slides[new_i])==prior_signatures[old_i]
    new=check.slides[2];texts=[sh.text for sh in new.shapes if sh.has_text_frame];pics=[sh for sh in new.shapes if sh.shape_type==MSO_SHAPE_TYPE.PICTURE]
    assert len(texts)==2 and len(pics)==3 and texts[0]==title and texts[1].replace('\v','').replace('\n','')==paragraph
    assert all(sh.left>=0 and sh.top>=0 and sh.left+sh.width<=check.slide_width and sh.top+sh.height<=check.slide_height for s in check.slides for sh in s.shapes)
    assert design.sha(original)==oldhash
    with zipfile.ZipFile(ppt) as z:assert z.testzip() is None
    (OUT/'verification.json').write_text(json.dumps(dict(state='seven_pages_added_dataset_slide_verified',inserted_page=3,old_six_slides_preserved=True,old_deck_sha256=oldhash,pptx_sha256=design.sha(ppt),frozen_counts_recomputed=True,total_pages=7,native_office_render_performed=False,production_writes=0),ensure_ascii=False,indent=2))
    with zipfile.ZipFile(OUT/'论文工作现状_7页完整包.zip','w',zipfile.ZIP_DEFLATED) as archive:
        for p in OUT.rglob('*'):
            if p.is_file() and p.suffix!='.zip':archive.write(p,p.relative_to(OUT))
    print(ppt);print(OUT/'previews/slide_03.png')


if __name__=='__main__':build()
