#!/usr/bin/env python3
"""
Task ID 리넘버링 스크립트
- task-10001.1 → task-1193.1
- task-10002.1 → task-1194.1

Usage:
  python3 renumber_remaining.py --dry-run   # 변경 사항 미리 보기
  python3 renumber_remaining.py             # 실제 실행
"""

import argparse
import json
from pathlib import Path

WORKSPACE_ROOT = Path("/home/jay/workspace")
MEMORY_ROOT = WORKSPACE_ROOT / "memory"

MAPPING = {
    "task-10001.1": "task-1193.1",
    "task-10002.1": "task-1194.1",
}

# 내용 치환에 사용할 패턴 목록 (순서 중요: 더 긴 것부터)
CONTENT_REPLACEMENTS = [
    ("task-10001.1", "task-1193.1"),
    ("task-10002.1", "task-1194.1"),
    ("task-10001", "task-1193"),  # 접미 .1 없는 참조도 처리
    ("task-10002", "task-1194"),
]


def log(dry_run: bool, action: str, detail: str):
    prefix = "[DRY-RUN] " if dry_run else "[DONE]    "
    print(f"{prefix}{action}: {detail}")


# ── 1. JSON 키 변경 ─────────────────────────────────────────────────────────


def rename_json_keys(filepath: Path, dry_run: bool):
    """task-timers.json / token-ledger.json 의 tasks 내 키 변경"""
    with open(filepath) as f:
        data = json.load(f)

    tasks = data.get("tasks", {})
    changed = 0
    for old_key, new_key in MAPPING.items():
        if old_key in tasks:
            entry = tasks.pop(old_key)
            # task_id 필드도 업데이트 (있을 경우)
            if isinstance(entry, dict) and "task_id" in entry:
                entry["task_id"] = new_key
            tasks[new_key] = entry
            changed += 1
            log(dry_run, "JSON key rename", f"{filepath.name}: '{old_key}' → '{new_key}'")

    if changed == 0:
        print(f"[SKIP]    JSON key rename: {filepath.name} — 대상 키 없음")
        return

    if not dry_run:
        data["tasks"] = tasks
        with open(filepath, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)


# ── 2. 파일명 변경 + 내용 치환 ──────────────────────────────────────────────


def rename_and_replace_file(old_path: Path, new_path: Path, dry_run: bool):
    """파일명 변경 + 내용 내 task ID 치환"""
    if not old_path.exists():
        print(f"[WARN]    파일 없음, 건너뜀: {old_path}")
        return

    with open(old_path, encoding="utf-8") as f:
        content = f.read()

    new_content = content
    for old, new in CONTENT_REPLACEMENTS:
        new_content = new_content.replace(old, new)

    replaced = content != new_content
    log(dry_run, "File rename + content replace", f"{old_path.name} → {new_path.name} (내용 변경: {replaced})")

    if not dry_run:
        with open(old_path, "w", encoding="utf-8") as f:
            f.write(new_content)
        old_path.rename(new_path)


# ── 3. 이벤트 파일 rename only ───────────────────────────────────────────────


def rename_event_file(old_path: Path, new_path: Path, dry_run: bool):
    """이벤트 파일: 이름만 변경, 내용 및 삭제 금지"""
    if not old_path.exists():
        print(f"[WARN]    이벤트 파일 없음, 건너뜀: {old_path}")
        return

    log(dry_run, "Event file rename", f"{old_path.name} → {new_path.name}")
    if not dry_run:
        old_path.rename(new_path)


# ── 4. 내용만 치환 (파일명 그대로) ──────────────────────────────────────────


def replace_content_only(filepath: Path, dry_run: bool):
    """파일명은 그대로, 내용 내 task ID만 치환"""
    if not filepath.exists():
        print(f"[WARN]    파일 없음, 건너뜀: {filepath}")
        return

    with open(filepath, encoding="utf-8") as f:
        content = f.read()

    new_content = content
    for old, new in CONTENT_REPLACEMENTS:
        new_content = new_content.replace(old, new)

    if content == new_content:
        print(f"[SKIP]    Content replace: {filepath.name} — 치환 대상 없음")
        return

    log(dry_run, "Content replace", f"{filepath.name}")
    if not dry_run:
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(new_content)


# ── Main ─────────────────────────────────────────────────────────────────────


def main():
    parser = argparse.ArgumentParser(description="Task ID 리넘버링: task-10001.1/10002.1 → 1193.1/1194.1")
    parser.add_argument("--dry-run", action="store_true", help="변경 없이 미리 보기만")
    args = parser.parse_args()
    dry_run = args.dry_run

    if dry_run:
        print("=" * 60)
        print("DRY-RUN 모드: 실제 파일 변경 없음")
        print("=" * 60)
    else:
        print("=" * 60)
        print("실행 모드: 파일 변경 시작")
        print("=" * 60)

    # 1. task-timers.json — tasks.task-10001.1 / tasks.task-10002.1 키 변경
    print("\n[Step 1] task-timers.json JSON 키 변경")
    rename_json_keys(MEMORY_ROOT / "task-timers.json", dry_run)

    # 2. token-ledger.json — tasks.task-10001.1 / tasks.task-10002.1 키 변경
    print("\n[Step 2] token-ledger.json JSON 키 변경")
    rename_json_keys(MEMORY_ROOT / "token-ledger.json", dry_run)

    # 3. tasks/ 파일명 + 내용 변경
    print("\n[Step 3] memory/tasks/ 파일 rename + 내용 치환")
    tasks_dir = MEMORY_ROOT / "tasks"
    rename_and_replace_file(
        tasks_dir / "task-10001.1.md",
        tasks_dir / "task-1193.1.md",
        dry_run,
    )
    rename_and_replace_file(
        tasks_dir / "task-10002.1.md",
        tasks_dir / "task-1194.1.md",
        dry_run,
    )

    # 4. reports/ 파일명 + 내용 변경
    print("\n[Step 4] memory/reports/ 파일 rename + 내용 치환")
    reports_dir = MEMORY_ROOT / "reports"
    rename_and_replace_file(
        reports_dir / "task-10001.1.md",
        reports_dir / "task-1193.1.md",
        dry_run,
    )
    rename_and_replace_file(
        reports_dir / "task-10002.1.md",
        reports_dir / "task-1194.1.md",
        dry_run,
    )

    # 5. events/ 파일 rename only (내용 변경 금지)
    print("\n[Step 5] memory/events/ 파일 rename (내용 변경 금지)")
    events_dir = MEMORY_ROOT / "events"
    event_renames = [
        ("task-10001.1.completion.txt", "task-1193.1.completion.txt"),
        ("task-10001.1.done.acked", "task-1193.1.done.acked"),
        ("task-10001.1.done.notified", "task-1193.1.done.notified"),
        ("task-10002.1.completion.txt", "task-1194.1.completion.txt"),
        ("task-10002.1.done.acked", "task-1194.1.done.acked"),
        ("task-10002.1.done.notified", "task-1194.1.done.notified"),
    ]
    for old_name, new_name in event_renames:
        rename_event_file(events_dir / old_name, events_dir / new_name, dry_run)

    # 6. 내용만 변경 (파일명 그대로)
    print("\n[Step 6] 내용 치환 (파일명 그대로)")
    replace_content_only(MEMORY_ROOT / "daily" / "2026-03-28.md", dry_run)
    replace_content_only(MEMORY_ROOT / "tasks" / "task-1197.1.md", dry_run)
    replace_content_only(MEMORY_ROOT / "tasks" / "dispatch-task-id-jump-fix.md", dry_run)
    replace_content_only(MEMORY_ROOT / "tasks" / "dispatch-renumber-remaining.md", dry_run)

    print("\n" + "=" * 60)
    if dry_run:
        print("DRY-RUN 완료. 실제 적용하려면 --dry-run 없이 재실행하세요.")
    else:
        print("리넘버링 완료!")
    print("=" * 60)


if __name__ == "__main__":
    main()
