"""Mutation 모듈 - SKILL.md에 딱 1가지 변경을 생성"""

from autoresearch.claude_runner import call_claude, estimate_tokens

MUTATION_PROMPT_TEMPLATE = """
당신은 스킬 프롬프트 최적화 전문가입니다.
아래 스킬 프롬프트에서 **딱 1가지만** 변경하세요.

변경 유형 (하나만 선택):
- 규칙 추가: 새로운 규칙이나 제약 조건 1개 추가
- 예시 삽입: 좋은 예시 1개 추가
- 금지 목록: 금지 단어/표현 목록 추가
- 표현 수정: 기존 지시문 1개의 표현을 더 명확하게 수정
- 구조 변경: 지시 순서나 섹션 구조 1곳 변경
- 규칙 삭제: 효과 없어 보이는 규칙 1개 제거

체크리스트를 참고하여, 가장 효과적일 것 같은 변경을 선택하세요.

[현재 스킬 프롬프트]
{current_skill_md}

[체크리스트]
{checklist_yaml}

[이전 변경 로그 (최근 5개)]
{recent_changelog}

응답 형식:
1. 첫 줄에 "변경 유형: <유형>" 명시
2. 둘째 줄에 "변경 설명: <설명>" 명시
3. 빈 줄 후 "---MODIFIED_SKILL---" 구분자
4. 구분자 아래에 변경된 전체 스킬 프롬프트 출력 (프론트매터 제외, 마크다운 본문만)
"""

_SEPARATOR = "---MODIFIED_SKILL---"


def build_mutation_prompt(current_skill_md: str, checklist_yaml: str, recent_changelog: str) -> str:
    """mutation 프롬프트를 조립"""
    return MUTATION_PROMPT_TEMPLATE.format(
        current_skill_md=current_skill_md,
        checklist_yaml=checklist_yaml,
        recent_changelog=recent_changelog,
    )


def parse_mutation_response(response_text: str) -> dict:
    """LLM 응답을 파싱하여 mutation 결과 반환.

    Returns:
        {
            "mutation_type": str,       # 변경 유형
            "mutation_description": str, # 변경 설명
            "modified_skill_md": str,    # 변경된 스킬 마크다운 본문
        }

    Raises ValueError if parsing fails.
    """
    if _SEPARATOR not in response_text:
        raise ValueError(f"응답에 구분자 '{_SEPARATOR}'가 없습니다. 응답: {response_text[:200]!r}")

    header_part, body_part = response_text.split(_SEPARATOR, 1)

    # 변경 유형 파싱
    mutation_type: str | None = None
    mutation_description: str | None = None

    for line in header_part.splitlines():
        stripped = line.strip()
        if stripped.startswith("변경 유형:"):
            mutation_type = stripped[len("변경 유형:") :].strip()
        elif stripped.startswith("변경 설명:"):
            mutation_description = stripped[len("변경 설명:") :].strip()

    if mutation_type is None:
        raise ValueError("응답에 '변경 유형:' 필드가 없습니다.")
    if mutation_description is None:
        raise ValueError("응답에 '변경 설명:' 필드가 없습니다.")

    # 구분자 바로 다음 줄부터 본문 (앞쪽 개행 1개 제거)
    modified_skill_md = body_part.lstrip("\n")
    # 뒤쪽 공백 제거
    modified_skill_md = modified_skill_md.rstrip()

    return {
        "mutation_type": mutation_type,
        "mutation_description": mutation_description,
        "modified_skill_md": modified_skill_md,
    }


def generate_mutation(
    current_skill_md: str,
    checklist_yaml: str,
    recent_changelog: str,
    model: str = "claude-sonnet-4-6",
) -> dict:
    """LLM을 호출하여 mutation 생성.

    Returns: parse_mutation_response 결과 + {"input_tokens": int, "output_tokens": int}
    """
    prompt = build_mutation_prompt(current_skill_md, checklist_yaml, recent_changelog)

    response_text = call_claude(prompt=prompt, model=model, max_tokens=8192)

    result = parse_mutation_response(response_text)
    result["input_tokens"] = estimate_tokens(prompt)
    result["output_tokens"] = estimate_tokens(response_text)

    return result
