#!/usr/bin/env python3
"""task-2729+3: merge_policy resolver.

task md 의 allowed_resources 블록에서 merge_policy 값을 파싱한다.
단일 책임·순수 함수. 외부 의존(네트워크/키/환경변수) 없음.

반환:
  - "none" | "tiered" | "auto" | "<value>" (소문자) — 명시된 경우
  - ""  — allowed_resources/merge_policy 미발견 (호출측 fail-CLOSED 신호)

종료 코드:
  - 0  — 정상(값은 stdout, 미발견이면 빈 문자열)
  - 2  — 인자/사용법 오류(argparse)

주의: finish-task.sh 는 본 resolver 를 2>/dev/null 없이 호출하므로,
      파싱 불가/예외는 fail-CLOSED 로 처리되도록 빈 문자열 또는 비-zero 종료로만 신호한다.
"""
from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path


def resolve_merge_policy(task_md_path) -> str:
    """task md 파일에서 allowed_resources.merge_policy 를 추출한다.

    allowed_resources: 마커 이후 최초의 merge_policy: 라인만 신뢰한다(본문 산문 오탐 방지).
    값의 따옴표/인라인주석(#)을 제거하고 소문자로 정규화한다.
    파일 미존재/디코딩 실패/미발견 시 빈 문자열을 반환한다(호출측이 fail-CLOSED 처리).
    """
    try:
        text = Path(task_md_path).read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError):
        return ""

    in_allowed = False
    for line in text.splitlines():
        if not in_allowed:
            if re.match(r"^\s*allowed_resources\s*:", line):
                in_allowed = True
            continue
        # allowed_resources 블록 진입 후: 코드펜스 종료(```)면 탐색 중단
        if line.strip().startswith("```"):
            break
        m = re.match(r"^\s*merge_policy\s*:\s*(.+?)\s*$", line)
        if m:
            value = m.group(1)
            value = value.split("#", 1)[0].strip()         # 인라인 주석 제거
            value = value.strip().strip('"').strip("'").strip()  # 따옴표 제거
            return value.lower()
    return ""


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description="Resolve merge_policy from a task md file.")
    parser.add_argument("--task-md", required=True, help="Path to the task markdown file.")
    args = parser.parse_args(argv)
    sys.stdout.write(resolve_merge_policy(args.task_md))
    return 0


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