"""등록된 작품 수정 — 발행(publish)과 같은 규칙으로 md·이미지·커밋을 다시 쓴다.""" from __future__ import annotations import json import re import shutil from pathlib import Path from typing import Any, Dict, List, Tuple import register as reg def parse_front(raw: str) -> Tuple[Dict[str, Any], str]: if not raw.startswith("---"): raise ValueError("md 파일이 --- 로 시작하지 않습니다") parts = raw.split("---", 2) if len(parts) != 3: raise ValueError("front matter 가 닫히지 않았습니다") front, body = parts[1], parts[2].lstrip("\n") data: Dict[str, Any] = {} key = "" for line in front.splitlines(): if not line.strip() or line.lstrip().startswith("#"): continue if line.startswith("- ") or line.startswith(" - "): if key: if not isinstance(data.get(key), list): data[key] = [] data[key].append(line.split("- ", 1)[1].strip().strip('"')) continue if ":" in line: key, value = line.split(":", 1) key, value = key.strip(), value.strip() if value == "": data[key] = [] elif value in ("true", "false"): data[key] = value == "true" elif re.fullmatch(r"-?\d+", value): data[key] = int(value) else: data[key] = value.strip('"') return data, body def render(data: Dict[str, Any], body: str) -> str: order = [k for k in reg.DEFAULT_ORDER if k in data] + [k for k in data if k not in reg.DEFAULT_ORDER] lines = ["---"] for key in order: value = data.get(key, "") if key == "gallery": lines.append("gallery:") for item in value or []: lines.append(f"- {reg._value(item)}") continue lines.append(f"{key}: {reg._value(value)}") lines.append("---") return "\n".join(lines) + "\n" + body.rstrip() + "\n" def _restage_images(slug: str, items: List[Dict[str, Any]]) -> List[str]: """items 순서대로 cover/detail-NN 으로 다시 배치한다. 기존 사진은 복사, 새 사진(uid)은 변환.""" image_dir = reg.ASSETS / "img" / slug image_dir.mkdir(parents=True, exist_ok=True) staged: List[Path] = [] inbox_sources: List[Path] = [] for index, item in enumerate(items): temp = image_dir / f".staging-{index:02d}.jpg" if item.get("uid"): source = reg.inbox_path(str(item["uid"])) reg._to_jpeg(source, temp) inbox_sources.append(source) else: rel = str(item.get("path") or "") existing = (reg.ROOT / rel).resolve() try: existing.relative_to(image_dir.resolve()) except ValueError as error: raise ValueError("이 작품 폴더의 사진만 쓸 수 있습니다") from error if not existing.is_file(): raise ValueError(f"사진이 없습니다: {rel}") shutil.copyfile(existing, temp) staged.append(temp) final: List[str] = [] for index, temp in enumerate(staged): name = "cover.jpg" if index == 0 else f"detail-{index:02d}.jpg" target = image_dir / name temp.replace(target) final.append(f"assets/img/{slug}/{name}") keep = {Path(path).name for path in final} for old in image_dir.glob("*.jpg"): if old.name not in keep: old.unlink(missing_ok=True) if reg.ARCHIVE and inbox_sources: archive_dir = reg.ARCHIVE / slug archive_dir.mkdir(parents=True, exist_ok=True) for index, source in enumerate(inbox_sources): shutil.copyfile(source, archive_dir / f"added-{index:02d}.jpg") for source in inbox_sources: source.unlink(missing_ok=True) return final def update_product(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]: slug = re.sub(r"[^a-z0-9-]+", "-", str(payload.get("slug") or "").lower()).strip("-") path = reg.PRODUCTS / f"{slug}.md" if not path.is_file(): raise FileNotFoundError(f"작품을 찾을 수 없습니다: {slug}") data, old_body = parse_front(path.read_text(encoding="utf-8")) items = payload.get("images") if isinstance(items, list) and items: final = _restage_images(slug, items) data["image"] = final[0] data["gallery"] = final[1:] for key in ("title", "subtitle", "price_note", "material", "size", "care", "image_alt", "naver_url"): if key in payload: data[key] = str(payload.get(key) or "").strip() if not str(data.get("title") or "").strip(): raise ValueError("제목을 비울 수 없습니다") if "price" in payload: digits = re.sub(r"[^0-9]", "", str(payload.get("price") or "")) data["price"] = int(digits) if digits and digits != "0" else "" for key in ("sold_out", "featured"): if key in payload: data[key] = bool(payload.get(key)) if payload.get("date"): date = str(payload["date"])[:10] if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date): data["date"] = date body = str(payload.get("body") or "").strip() or old_body original = path.read_bytes() path.write_text(render(data, body), encoding="utf-8") ok, log = helpers["build"]() if not ok: path.write_bytes(original) raise RuntimeError(f"빌드 실패로 수정을 되돌렸습니다: {log[-300:]}") image_dir = reg.ASSETS / "img" / slug commit_ok, commit_log = helpers["git_commit"]( f"작품 수정: {data.get('title')}", [str(path.relative_to(reg.ROOT)), str(image_dir.relative_to(reg.ROOT))]) if not commit_ok: raise RuntimeError(f"커밋 실패: {commit_log}") push_ok, push_log = True, "" if helpers.get("push"): push_ok, push_log = helpers["push"]() deploy_ok, deploy_log = (True, "배포하지 않음") if payload.get("deploy"): deploy_ok, deploy_log = helpers["deploy"]() return {"ok": True, "slug": slug, "commit": commit_log, "deployed": bool(payload.get("deploy")) and deploy_ok, "pushed": push_ok, "build_log": log[-300:], "deploy_log": deploy_log[-300:], "url": f"/p/{slug}.html"} def rewrite_body(slug: str, tone: str) -> Dict[str, Any]: """기존 본문을 다른 어투로 다시 쓴다(저장은 사람이 확인하고 한다).""" slug = re.sub(r"[^a-z0-9-]+", "-", str(slug or "").lower()).strip("-") path = reg.PRODUCTS / f"{slug}.md" if not path.is_file(): raise FileNotFoundError(f"작품을 찾을 수 없습니다: {slug}") data, body = parse_front(path.read_text(encoding="utf-8")) guide = reg.TONES.get(tone) or reg.TONES[reg.DEFAULT_TONE] system = reg.tone_system(tone) + ( "\n\n지금 할 일: 아래 '지금 본문'을 같은 사실 그대로 두고 어투만 바꿔 다시 쓴다." "\n- 재료·규격·가격·기간 같은 값은 바꾸지 않는다. 없는 사실을 더하지 않는다." "\n- 문단 수는 2~4개를 지킨다." '\n응답은 설명 없이 JSON 하나: {"body": "새 본문 전문"}' ) user = json.dumps({ "제목": str(data.get("title") or ""), "부제": str(data.get("subtitle") or ""), "소재": str(data.get("material") or ""), "규격": str(data.get("size") or ""), "지금_본문": body.strip(), "지금_어투": "지금 본문의 어미를 물려받지 말고, 문장 종결 어미를 반드시 위 어투로 바꾼다", }, ensure_ascii=False, indent=2) result = reg._ai_json(system, user) new_body = str((result.get("data") or {}).get("body") or "").strip() if not new_body: raise RuntimeError("AI가 본문을 만들지 못했습니다 — 다시 눌러 주세요") return {"ok": True, "slug": slug, "tone": tone, "tone_label": guide["label"], "before": body.strip(), "body": new_body, "tokens": result.get("tokens")}