from cad_kernel import load as cadquery
from pathlib import Path
from tempfile import TemporaryDirectory
from datetime import datetime
from uuid import uuid4
from model import export_step

def publish_export(parent, prefix, write):
    """Publish a complete output directory on the selected filesystem."""
    parent=Path(parent)
    stamp=datetime.now().strftime('%Y%m%d_%H%M%S')
    final=parent/f'{prefix}_{stamp}_{uuid4().hex[:8]}'
    with TemporaryDirectory(prefix='.boltstudio-',dir=parent) as temporary:
        staging=Path(temporary)/'output'
        write(staging)
        staging.rename(final)
    return final


def export_cad(shapes,out,fmt,log=print):
    cq=cadquery()
    out=Path(out);out.mkdir(parents=True,exist_ok=False)
    names=('bolt','nut','washer','spring_washer')
    actual=[(n,s) for n,s in zip(names,shapes) if s is not None]
    if fmt=='step':export_step(shapes,out)
    elif fmt=='igs':
        from OCP.IGESControl import IGESControl_Writer
        for name,shape in actual+[('assembly',cq.Compound.makeCompound([s for _,s in actual]))]:
            writer=IGESControl_Writer('MM',1)
            if not writer.AddShape(shape.wrapped):raise RuntimeError('IGS 转换失败：'+name)
            writer.ComputeModel()
            if not writer.Write(str(out/(name+'.igs'))):raise RuntimeError('IGS 写入失败：'+name)
    else:raise ValueError('未知格式')
    return out
