from pptx import Presentation
from pptx.util import Inches
import textwrap

# Read the report text
with open('260721_semiconductor_expanded_report.txt','r',encoding='utf8') as f:
    txt = f.read()

# Helper to extract section between headings
def extract_section(start_keyword, end_keywords):
    start = txt.find(start_keyword)
    if start == -1:
        return ''
    # find earliest end keyword after start
    end = len(txt)
    for k in end_keywords:
        idx = txt.find(k, start+1)
        if idx != -1 and idx < end:
            end = idx
    return txt[start:end].strip()

prs = Presentation()
prs.slide_width = Inches(13.33)
prs.slide_height = Inches(7.5)

# Title slide
slide = prs.slides.add_slide(prs.slide_layouts[0])
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "260721 Semiconductor Expanded Report"
subtitle.text = "Compiled: 2026-07-23    Prepared by: zeroclaw 🦀"

# Exec summary slide
exec_text = extract_section('Executive Summary', ['Detailed News Summaries & Analysis','1) HBM4'])
slide = prs.slides.add_slide(prs.slide_layouts[1])
slide.shapes.title.text = 'Executive Summary'
body = slide.shapes.placeholders[1].text_frame
for line in exec_text.splitlines():
    line = line.strip()
    if not line:
        continue
    p = body.add_paragraph()
    p.level = 0
    p.text = line

# Function to add content slide
def add_content_slide(title_text, content_text, notes_text=None):
    slide = prs.slides.add_slide(prs.slide_layouts[1])
    slide.shapes.title.text = title_text
    tf = slide.shapes.placeholders[1].text_frame
    for para in content_text.split('\n'):
        para = para.strip()
        if not para:
            continue
        p = tf.add_paragraph()
        p.level = 0
        wrapped = '\n'.join(textwrap.wrap(para, width=110))
        p.text = wrapped
    if notes_text:
        notes = slide.notes_slide.notes_text_frame
        notes.text = notes_text

# Slides for each major item
hbm = extract_section('1) HBM4', ['2) SEMI','Detailed News Summaries & Analysis'])
if not hbm:
    hbm = extract_section('1) HBM4 수율 경쟁 본격화', ['2) SEMI'])

semi = extract_section('2) SEMI', ['3) 국내','Detailed News Summaries & Analysis'])
if not semi:
    semi = extract_section('2) SEMI 전망', ['3) 국내'])

domestic = extract_section('3) 국내', ['4) 중국','Detailed News Summaries & Analysis'])
china = extract_section('4) 중국', ['5) 기관','Detailed News Summaries & Analysis'])
inst = extract_section('5) 기관', ['Cross-cutting Themes','Detailed News Summaries & Analysis'])

# Clean texts
hbm = hbm.replace('\n- ','\n').replace('1) HBM4 수율 경쟁 본격화','').strip()
semi = semi.replace('\n- ','\n').replace('2) SEMI 전망 — 장비시장 대규모 성장','').strip()
domestic = domestic.replace('\n- ','\n').strip()
china_inst = (china + '\n' + inst).strip()

add_content_slide('HBM4 수율 경쟁 (요약 & 시사점)', hbm, notes_text='모니터링 KPI: 양산 발표일, 수율 추정치, 고객 확보 공시 등')
add_content_slide('SEMI 전망 — 장비시장', semi, notes_text='숫자: 2028년 약 2295억 달러 전망. KPI: 장비주 수주공시 등')
add_content_slide('국내 투자·정책 모멘텀', domestic, notes_text='집행 일정과 세부조건 확인 필요')
add_content_slide('중국 AI·기관 수급 동향', china_inst, notes_text='지정학 리스크 및 기관 포지셔닝 주시')

# Actions & Monitoring
actions = extract_section('Actionable Recommendations', ['Monitoring Checklist','Next Steps'])
monitor = extract_section('Monitoring Checklist', ['Next Steps','Appendix'])
notes = extract_section('Risks & Caveats', ['Actionable Recommendations','Monitoring Checklist'])

add_content_slide('권장 액션 (요약)', actions, notes_text='우선순위 기반으로 0-2주/2-8주/1-6개월 계획 제시')
add_content_slide('모니터링 체크리스트', monitor, notes_text='HBM4/장비시장/정책/지정학/수급 항목 포함')

# Appendix
appendix = extract_section('Appendix', ['파일 저장','원하시는 다음 단계'])
if not appendix:
    appendix = extract_section('Risks & Caveats', ['Actionable Recommendations'])
add_content_slide('Appendix & Notes', appendix)

# Save
outname = '260721_semiconductor_report.pptx'
prs.save(outname)
print('Saved', outname)
