"""본심 최종 검증: 샘플 이미지 구조 정확히 반영.

구조: 왼쪽 텍스트(넓게) | 오른쪽 이미지(좁게) + 상단 팝업 링크
텍스트: 원본 MDX 거의 그대로, 축약 없음
"""
from __future__ import annotations
import asyncio, sys, datetime, base64
from pathlib import Path

ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(ROOT))


async def main():
    from src.slide_measurer import capture_slide_screenshot

    out_dir = ROOT / "data" / "runs" / f"core_final_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"
    out_dir.mkdir(parents=True, exist_ok=True)

    # dx1.png base64
    img_path = Path("D:/ad-hoc/cel/public/assets/images/dx1.png")
    img_b64 = base64.b64encode(img_path.read_bytes()).decode()
    img_src = f"data:image/png;base64,{img_b64}"

    html = f"""<style>
* {{ margin:0; padding:0; box-sizing:border-box; }}
.core-section {{
    width: 707px;
    height: 293px;
    font-family: 'Pretendard Variable', sans-serif;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 16px 20px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}}
.core-header {{
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
}}
.core-title {{
    background: #1e293b;
    color: #ffffff;
    font-size: 13px;
    font-weight: 700;
    padding: 4px 14px;
    border-radius: 4px;
}}
.core-detail-link {{
    font-size: 10px;
    color: #2563eb;
    font-weight: 700;
    cursor: pointer;
    text-decoration: underline;
}}
.core-body {{
    display: flex;
    gap: 16px;
    flex: 1;
}}
.core-text {{
    flex: 62%;
    font-size: 12px;
    color: #1e293b;
    line-height: 1.7;
}}
.core-text .main-point {{
    margin-bottom: 8px;
}}
.core-text .main-point::before {{
    content: '•';
    margin-right: 6px;
    color: #1e293b;
    font-weight: 700;
}}
.core-text .sub-point {{
    padding-left: 16px;
    font-size: 11px;
    color: #475569;
    margin-bottom: 4px;
}}
.core-text .sub-point::before {{
    content: '◦';
    margin-right: 6px;
    color: #64748b;
}}
.core-text b {{
    font-weight: 700;
    color: #1e293b;
}}
.core-image {{
    flex: 38%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}}
.core-image img {{
    width: 100%;
    border-radius: 6px;
    border: 1px solid #e2e8f0;
    object-fit: contain;
}}
.core-image .caption {{
    font-size: 9px;
    color: #94a3b8;
    margin-top: 4px;
    text-align: center;
}}

/* 팝업 테이블 */
.core-detail-link details {{
    position: relative;
}}
.core-detail-link summary {{
    font-size: 10px;
    color: #2563eb;
    font-weight: 700;
    cursor: pointer;
    list-style: none;
}}
.core-detail-link summary::-webkit-details-marker {{
    display: none;
}}
.popup-table {{
    position: absolute;
    right: 0;
    top: 20px;
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    padding: 8px;
    z-index: 10;
    width: 500px;
}}
.popup-table table {{
    width: 100%;
    border-collapse: collapse;
    font-size: 10px;
}}
.popup-table th {{
    background: #1e293b;
    color: white;
    padding: 5px 8px;
    text-align: left;
    font-weight: 700;
}}
.popup-table td {{
    padding: 4px 8px;
    border-bottom: 1px solid #e2e8f0;
    color: #334155;
}}
.popup-table tr:nth-child(even) {{
    background: #f8fafc;
}}
</style>

<div class="core-section">
    <div class="core-header">
        <div class="core-title">DX와 BIM의 관계</div>
        <div class="core-detail-link">
            <details>
                <summary>📊 DX와 BIM의 상세 비교</summary>
                <div class="popup-table">
                    <table>
                        <tr><th>기준</th><th>DX</th><th>BIM</th></tr>
                        <tr><td>범위</td><td>BIM &lt;&lt; DX (Engineering + Management 통합)</td><td>Only 3D (형상 구현 중심)</td></tr>
                        <tr><td>프로세스</td><td>근본적 문제의식을 통한 개선</td><td>기존 2D 설계 방식 유지</td></tr>
                        <tr><td>성과품</td><td>공학 정보 및 콘텐츠 연계에 집중</td><td>3D 모델 중심</td></tr>
                        <tr><td>활용</td><td>설계/시공 생산성 혁신</td><td>3D 모델에 의한 일반적 이해 향상</td></tr>
                        <tr><td>확장성</td><td>전 생애주기 활용 시스템</td><td>(설계/시공/운영) 분야별 단절</td></tr>
                        <tr><td>주체</td><td>자체 수행 능력 — 지속가능성 확보</td><td>S/W 제작사 판매 정책에 의존</td></tr>
                    </table>
                </div>
            </details>
        </div>
    </div>
    <div class="core-body">
        <div class="core-text">
            <div class="main-point">DX는 BIM과 같은 기술을 기반으로 산업 전반의 <b>프로세스를 혁신하는 상위개념</b></div>
            <div class="main-point">건설산업의 DX는 GIS(공간정보), BIM, 디지털 트윈(가상환경)의 <b>기술융합을 통해서만 실현 또는 구현 가능</b></div>
            <div class="sub-point"><b>GIS의 역할</b> : 지리적 데이터를 공간 분석하여 시각적으로 표현, 위치기반 정보 제공</div>
            <div class="sub-point"><b>BIM의 역할</b> : 형상정보와 내용정보가 포함된 3D모델로, 건설 정보 기반의 <b>Process와 Product를 제공</b></div>
        </div>
        <div class="core-image">
            <img src="{img_src}" alt="건설산업의 DX">
            <div class="caption">건설산업의 DX</div>
        </div>
    </div>
</div>"""

    wrapped = f"""<!DOCTYPE html>
<html lang="ko"><head><meta charset="UTF-8">
<style>
@import url('https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css');
* {{ margin:0; padding:0; box-sizing:border-box; }}
.slide {{
    width:1280px; height:720px; overflow:hidden; background:white;
    font-family:'Pretendard Variable',sans-serif;
    display:flex; align-items:center; justify-content:center;
}}
</style>
</head><body>
<div class="slide">
{html}
</div>
</body></html>"""

    (out_dir / "core_final.html").write_text(wrapped, encoding="utf-8")
    s = await asyncio.to_thread(capture_slide_screenshot, wrapped)
    if s:
        (out_dir / "core_final.png").write_bytes(base64.b64decode(s))

    print(f"결과: {out_dir}")


if __name__ == "__main__":
    import logging
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S")
    logging.getLogger("selenium").setLevel(logging.WARNING)
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    asyncio.run(main())
