"""Regenerate only the episode section of the offline Studio gallery."""
from __future__ import annotations

import argparse
import html
from pathlib import Path
import re
import tempfile
import time
from urllib.parse import quote

ROOT = Path(__file__).resolve().parent
START = '<!-- EPISODES:BEGIN -->'
END = '<!-- EPISODES:END -->'


def inside(path: Path, root: Path) -> bool:
    return path.resolve().is_relative_to(root.resolve())


def metadata(episode: Path) -> dict[str, str]:
    values = dict(title=episode.name, style='미기록', duration='미확인', status='준비')
    readme = episode / 'README.md'
    if not readme.is_file() or not inside(readme, episode):
        return values
    text = readme.read_text(encoding='utf-8-sig')
    heading = re.search(r'^#\s+(.+)$', text, re.M)
    if heading:
        values['title'] = heading[1].strip()
    rows = [line.strip().strip('|').strip().split('|') for line in text.splitlines()
            if line.lstrip().startswith('|')]
    for index, cells in enumerate(rows):
        headers = [cell.strip() for cell in cells]
        if '제목' not in headers or '상태' not in headers:
            continue
        for data in rows[index + 1:]:
            data = [cell.strip() for cell in data]
            if all(re.fullmatch(r'[:\s-]*', cell) for cell in data):
                continue
            mapping = dict(zip(headers, data))
            for source, target in [('제목', 'title'), ('스타일', 'style'),
                                   ('길이', 'duration'), ('상태', 'status')]:
                if mapping.get(source):
                    values[target] = mapping[source]
            return values
    return values


def url(path: Path, root: Path) -> str:
    return quote(path.relative_to(root).as_posix(), safe='/')


def media(episode: Path) -> tuple[Path | None, Path | None, bool]:
    out = episode / 'out'
    if not out.is_dir() or not inside(out, episode):
        return None, None, False
    final = out / 'final.mp4'
    complete = final.is_file() and inside(final, episode) and final.stat().st_size > 0
    candidates = sorted((p for p in out.rglob('*.mp4')
                         if p.is_file() and inside(p, episode) and p.stat().st_size > 0),
                        key=lambda p: p.as_posix())
    video = final if complete else next(iter(candidates), None)
    # Prefer a contact sheet over a browser screenshot containing account UI.
    images = sorted((p for p in out.rglob('*') if p.suffix.lower() in {'.png', '.jpg', '.jpeg', '.webp'}
                     and p.is_file() and inside(p, episode) and p.name != 'direct-screen.png'),
                    key=lambda p: ('contact-sheet' not in p.name, p.as_posix()))
    return video, next(iter(images), None), complete


def episode_card(episode: Path, root: Path) -> str:
    info = metadata(episode)
    video, poster, complete = media(episode)
    status = info['status']
    if complete and status in {'준비', '진행 중', '제작 중'}:
        status = '영상 있음 · 검수 확인 필요'
    elif not complete and status == '완성':
        status = '클립만 있음' if video else '영상 없음'
    esc = html.escape
    if video:
        poster_attr = f' poster="{url(poster, root)}"' if poster else ''
        preview = f'<video controls preload="metadata"{poster_attr} src="{url(video, root)}"></video>'
    elif poster:
        preview = f'<img src="{url(poster, root)}" alt="{esc(info["title"], quote=True)} 미리보기" style="width:100%;height:100%;object-fit:contain">'
    else:
        preview = '<div class="placeholder-overlay"><span>준비 중</span></div>'
    note = '<p class="meta-value">클립 미리보기 · 최종본 준비 중</p>' if video and not complete else ''
    links = []
    for name in ('README.md', 'SPEC.md', 'REVIEW.md'):
        path = episode / name
        if path.is_file() and inside(path, episode):
            links.append(f'<a class="doc-link" href="{url(path, root)}">{name}</a>')
    badge = 'done' if complete and status == '완성' else 'prep'
    details = '\n'.join(
        f'              <div class="meta-item"><span class="meta-label">{label}</span>'
        f'<span class="meta-value">{esc(value)}</span></div>'
        for label, value in [('폴더명', episode.name), ('스타일', info['style']), ('길이', info['duration'])])
    return f'''        <article class="episode-card">
          <div class="video-wrapper">{preview}</div>
          <div class="card-body">
            <div class="card-header"><h3 class="card-title">{esc(info['title'])}</h3><span class="badge {badge}">{esc(status)}</span></div>
            {note}
            <div class="meta-list">
{details}
            </div>
            <div class="card-footer">{' '.join(links)}</div>
          </div>
        </article>'''


def render(root: Path) -> tuple[str, int]:
    episodes_root = root / 'episodes'
    if not episodes_root.is_dir():
        raise ValueError(f'Episodes directory not found: {episodes_root}')
    episodes = sorted((p for p in episodes_root.iterdir()
                       if p.is_dir() and not p.name.startswith('.') and inside(p, episodes_root)),
                      key=lambda p: p.name, reverse=True)
    cards = '\n\n'.join(episode_card(p, root) for p in episodes)
    return f'''    {START}
    <section>
      <h2 class="section-title">📽️ 에피소드 목록 ({len(episodes)}개)</h2>
      <div class="episode-grid">
{cards}
      </div>
    </section>
    {END}''', len(episodes)


def update(root: Path = ROOT) -> tuple[bool, int]:
    gallery = root / 'gallery.html'
    with gallery.open(encoding='utf-8-sig', newline='') as source:
        old = source.read()
    block, count = render(root)
    newline = '\r\n' if '\r\n' in old else '\n'
    block = block.replace('\n', newline)
    pattern = (r'    <!-- EPISODES:BEGIN -->.*?    <!-- EPISODES:END -->'
               if START in old else
               r'    <!-- 에피소드 그리드 섹션 -->.*?(?=\s*<!-- 스타일 섹션 -->)')
    matches = list(re.finditer(pattern, old, re.S))
    if len(matches) != 1:
        raise ValueError('Expected exactly one episode section; gallery left unchanged')
    match = matches[0]
    suffix = newline * 2 if START not in old else ''
    new = old[:match.start()] + block + suffix + old[match.end():]
    if new == old:
        return False, count
    temp = None
    try:
        with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', newline='',
                                         dir=root, prefix='.gallery-', suffix='.tmp', delete=False) as target:
            temp = Path(target.name)
            target.write(new)
        temp.replace(gallery)
    finally:
        if temp and temp.exists():
            temp.unlink()
    return True, count


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--watch', action='store_true', help='Watch episodes every 3 seconds; Ctrl+C to stop')
    args = parser.parse_args()
    try:
        while True:
            changed, count = update()
            if changed or not args.watch:
                print(f'Gallery {"updated" if changed else "unchanged"}: {count} episodes', flush=True)
            if not args.watch:
                return 0
            time.sleep(3)
    except KeyboardInterrupt:
        return 0
    except (OSError, ValueError) as error:
        print(f'Gallery update failed: {error}')
        return 1


if __name__ == '__main__':
    raise SystemExit(main())
