import re, sys, io

path = sys.argv[1]
with io.open(path, "r", encoding="utf-8") as f:
    src = f.read()

# ── 1. 헤더 주석 교체 ────────────────────────────────
old_header_start = src.index("/* volnew1/js/custom.js")
old_header_end = src.index("*/", old_header_start) + 2
new_header = """/* vol1/js/custom.js
 * 안성마춤 웹진 — 데이터 기반 렌더러.
 * data.json 의 sections[] 순서를 그대로 따른다 (7개 고정 편집 레이아웃 전제):
 *   0: FOCUS                  → 섹션2 풀블리드, 왼쪽 텍스트
 *   1: PEOPLE                 → 섹션3 풀블리드, 오른쪽 텍스트
 *   2: ONE DAY, 3: HOME TABLE → 섹션4 2x2 엇갈림 모자이크
 *   4: SEASON PICK            → 섹션5 배너
 *   5: MARKET, 6: LOCAL BRAND → 섹션6 카드
 * 섹션 수가 달라져도 화면이 깨지지 않도록 각 렌더 함수는 배열 길이를 확인한다.
 */"""
src = src[:old_header_start] + new_header + src[old_header_end:]

# ── 2. 엘리먼트 참조 블록 교체 ───────────────────────
old_refs = """  var featureEl = document.getElementById('ansungFeature');
  var pairEl = document.getElementById('ansungPair');
  var bannerEl = document.getElementById('ansungBanner');
  var cardrowEl = document.getElementById('ansungCardrow');
  var galleryEl = document.getElementById('ansungGallery');"""
new_refs = """  var focusEl = document.getElementById('sectionFocus');
  var peopleEl = document.getElementById('sectionPeople');
  var mosaicEl = document.getElementById('mosaicGrid');
  var bannerEl = document.getElementById('bannerBox');
  var cardsEl = document.getElementById('cardsGrid');"""
assert old_refs in src, "refs block not found"
src = src.replace(old_refs, new_refs)

src = src.replace(
    "var volBadgeEl = document.getElementById('ansungVolBadge');",
    "var volBadgeEl = document.getElementById('volBadge');",
)
src = src.replace(
    "var isIndex = !!(heroTitle || featureEl);",
    "var isIndex = !!(heroTitle || focusEl);",
)

# ── 3. renderFeature → renderFocus/renderPeople + renderMosaic 교체 ──
start = src.index("  /* 1~2번째 섹션:")
end = src.index("  /* 5번째 섹션:")
new_block = '''  /* 섹션 2·3: 풀블리드 이미지 + 오버레이 텍스트 (FOCUS 좌 / PEOPLE 우) */
  function featureMarkup(section, side) {
    var thumb = resolveAsset(section.thumbnail || '');
    var sideClass = side === 'right' ? ' feature--right' : '';
    return (
      '<a class="feature' + sideClass + '" href="' + sectionHref(section) + '">' +
        (thumb ? '<img class="feature__img" src="' + esc(thumb) + '" alt="' + esc(loc(section, 'SectionName')) + '" loading="lazy">' : '') +
        '<div class="feature__scrim" aria-hidden="true"></div>' +
        '<div class="feature__body section__inner">' +
          '<div class="feature__text">' +
            '<p class="feature__kicker">' + esc(loc(section, 'SectionName')) + '</p>' +
            '<h2 class="feature__title">' + loc(section, 'desc') + '</h2>' +
            '<p class="feature__summary">' + loc(section, 'summary') + '</p>' +
            (loc(section, 'author') ? '<p class="feature__author">' + esc(loc(section, 'author')) + '</p>' : '') +
          '</div>' +
        '</div>' +
      '</a>'
    );
  }

  function renderFocus(sections) {
    if (!focusEl) return;
    var section = sections[0];
    if (!section) { focusEl.hidden = true; return; }
    focusEl.innerHTML = featureMarkup(section, 'left');
  }

  function renderPeople(sections) {
    if (!peopleEl) return;
    var section = sections[1];
    if (!section) { peopleEl.hidden = true; return; }
    peopleEl.innerHTML = featureMarkup(section, 'right');
  }

  /* 섹션 4: 2x2 엇갈림 모자이크 (ONE DAY 사진좌/글우, HOME TABLE 글좌/사진우) */
  function renderMosaic(sections) {
    if (!mosaicEl) return;
    var items = sections.slice(2, 4);
    if (!items.length) { mosaicEl.closest('.mosaic-section').hidden = true; return; }

    function mediaCell(section, placement) {
      var thumb = resolveAsset(section.thumbnail || '');
      if (!thumb) return '<span class="mosaic__cell mosaic__cell--' + placement + '"></span>';
      return (
        '<a class="mosaic__media mosaic__cell mosaic__cell--' + placement + '" href="' + sectionHref(section) + '">' +
          '<img src="' + esc(thumb) + '" alt="' + esc(loc(section, 'SectionName')) + '" loading="lazy">' +
        '</a>'
      );
    }

    function panelCell(section, placement) {
      return (
        '<a class="mosaic__panel mosaic__cell mosaic__cell--' + placement + '" href="' + sectionHref(section) + '">' +
          '<p class="mosaic__kicker">' + esc(loc(section, 'SectionName')) + '</p>' +
          '<h3 class="mosaic__title">' + loc(section, 'desc') + '</h3>' +
          '<p class="mosaic__summary">' + loc(section, 'summary') + '</p>' +
        '</a>'
      );
    }

    var html = '';
    // 1행: 사진(좌) + 텍스트(우)
    if (items[0]) {
      html += mediaCell(items[0], 'media-left') + panelCell(items[0], 'panel-right');
    }
    // 2행: 텍스트(좌) + 사진(우)
    if (items[1]) {
      html += panelCell(items[1], 'panel-left') + mediaCell(items[1], 'media-right');
    }
    mosaicEl.innerHTML = html;
  }

'''
src = src[:start] + new_block + src[end:]

# ── 4. renderBanner 교체 ─────────────────────────────
bstart = src.index("  /* 5번째 섹션:")
bend = src.index("  /* 6~7번째 섹션:")
new_banner = '''  /* 섹션 5: 배너 (좌 이미지 + 우 캡션 패널, SEASON PICK) */
  function renderBanner(sections) {
    if (!bannerEl) return;
    var section = sections[4];
    if (!section) { bannerEl.closest('.banner-section').hidden = true; return; }

    var thumb = resolveAsset(section.thumbnail || '');
    bannerEl.innerHTML =
      (thumb
        ? '<a class="banner__media" href="' + sectionHref(section) + '">' +
            '<img src="' + esc(thumb) + '" alt="' + esc(loc(section, 'SectionName')) + '" loading="lazy">' +
          '</a>'
        : '') +
      '<div class="banner__text">' +
        '<a class="banner__badge" href="' + sectionHref(section) + '">' +
          '<p class="banner__kicker">' + esc(loc(section, 'SectionName')) + '</p>' +
          '<h3 class="banner__title">' + loc(section, 'desc') + '</h3>' +
        '</a>' +
        '<p class="banner__summary">' + loc(section, 'summary') + '</p>' +
      '</div>';
  }

'''
src = src[:bstart] + new_banner + src[bend:]

# ── 5. renderCardrow → renderCards, renderGallery 삭제 ──
cstart = src.index("  /* 6~7번째 섹션:")
gend = src.index("  /**\n   * data.json meta.pdf")
new_cards = '''  /* 섹션 6: 2단 카드 (MARKET / LOCAL BRAND) */
  function renderCards(sections) {
    if (!cardsEl) return;
    var items = sections.slice(5, 7);
    if (!items.length) { cardsEl.closest('.cards-section').hidden = true; return; }

    cardsEl.innerHTML = items.map(function (section) {
      var thumb = resolveAsset(section.thumbnail || '');
      return (
        '<a class="card" href="' + sectionHref(section) + '">' +
          (thumb ? '<div class="card__media"><img src="' + esc(thumb) + '" alt="' + esc(loc(section, 'SectionName')) + '" loading="lazy"></div>' : '') +
          '<div class="card__text">' +
            '<h3 class="card__title">' + esc(loc(section, 'SectionName')) + '</h3>' +
            '<p class="card__desc">' + loc(section, 'desc') + '</p>' +
          '</div>' +
        '</a>'
      );
    }).join('');
  }

'''
src = src[:cstart] + new_cards + src[gend:]

# ── 6. 렌더 호출부 교체 ──────────────────────────────
old_calls = """        renderFeature(sections);
        renderPair(sections);
        renderBanner(sections);
        renderCardrow(sections);
        renderGallery(sections);"""
new_calls = """        renderFocus(sections);
        renderPeople(sections);
        renderMosaic(sections);
        renderBanner(sections);
        renderCards(sections);"""
assert old_calls in src, "render calls not found"
src = src.replace(old_calls, new_calls)

# ── 7. 잔여 ansung- 문자열 정리 (sessionStorage 키 등) ──
src = src.replace("'ansung-side-quick'", "'wz-side-quick'")
src = src.replace("'[ansung]", "'[webzine]")
src = src.replace("[ansung] data.json", "[webzine] data.json")

with io.open(path, "w", encoding="utf-8") as f:
    f.write(src)

leftovers = re.findall(r"ansung[-A-Z][A-Za-z0-9_-]*", src)
print("remaining ansung tokens:", sorted(set(leftovers)) or "none")
print("OK")
