"""스킬 실행 모듈 - SKILL.md를 로드하고 claude -p CLI로 실행"""

import os
from pathlib import Path
from typing import Optional

from autoresearch.claude_runner import call_claude, estimate_tokens

_WORKSPACE_ROOT = os.environ.get(
    "WORKSPACE_ROOT", str(Path(__file__).resolve().parent.parent.parent)
)


def load_env_key(key_name: str = "ANTHROPIC_API_KEY") -> str:
    """[deprecated] load_auth() 사용 권장. 하위호환용.

    환경변수 → .env.keys → .env 순서로 API 키를 찾아 반환.

    Raises:
        EnvironmentError: 키를 찾을 수 없는 경우
    """
    # 1. 환경변수에서 먼저 찾기
    value = os.environ.get(key_name)
    if value:
        return value

    # 검색할 파일 목록 (우선순위 순)
    search_paths: list[Path] = []

    # 현재 작업 디렉토리 기준 파일
    cwd = Path.cwd()
    search_paths.append(cwd / ".env.keys")
    search_paths.append(cwd / ".env")

    # 홈 디렉토리 기준 파일
    home = Path.home()
    search_paths.append(home / ".env.keys")
    search_paths.append(home / ".env")

    for env_file in search_paths:
        try:
            content = env_file.read_text(encoding="utf-8")
            for line in content.splitlines():
                line = line.strip()
                if line.startswith("#") or "=" not in line:
                    continue
                file_key, _, file_value = line.partition("=")
                # "export KEY=VALUE" 형식 지원
                key_stripped = file_key.strip()
                if key_stripped.startswith("export "):
                    key_stripped = key_stripped[len("export ") :].strip()
                if key_stripped == key_name:
                    val = file_value.strip()
                    if val:
                        return val
        except (FileNotFoundError, PermissionError, OSError):
            continue

    raise EnvironmentError(f"API key '{key_name}' not found in environment variables, " ".env.keys, or .env files.")


def load_skill(skill_name: str, skills_dir: str = str(Path(_WORKSPACE_ROOT) / "skills")) -> tuple[str, str]:
    """SKILL.md를 로드하여 (frontmatter, body) 반환.

    Args:
        skill_name: 스킬 이름 (디렉토리명)
        skills_dir: 스킬 디렉토리 경로

    Returns:
        (frontmatter, body) 튜플.
        frontmatter는 YAML 프론트매터 문자열 (--- 구분자 제외),
        body는 마크다운 본문.

    Raises:
        FileNotFoundError: SKILL.md 파일이 없는 경우
    """
    skill_path = Path(skills_dir) / skill_name / "SKILL.md"

    if not skill_path.exists():
        raise FileNotFoundError(f"SKILL.md not found: {skill_path}")

    content = skill_path.read_text(encoding="utf-8")

    # YAML 프론트매터 파싱: --- 로 시작하고 --- 로 끝나는 블록
    frontmatter = ""
    body = content

    if content.startswith("---"):
        # 첫 번째 --- 이후에서 두 번째 --- 찾기
        lines = content.splitlines(keepends=True)
        # 첫 줄은 '---'
        end_index = -1
        for i, line in enumerate(lines[1:], start=1):
            if line.rstrip() == "---":
                end_index = i
                break

        if end_index != -1:
            # frontmatter: 첫 번째 --- 와 마지막 --- 사이 내용
            frontmatter = "".join(lines[1:end_index]).rstrip()
            # body: 두 번째 --- 이후 내용 (앞의 공백 제거)
            body = "".join(lines[end_index + 1 :]).lstrip("\n")

    return frontmatter, body


def execute_skill(
    skill_body: str,
    test_input: str,
    model: str = "claude-sonnet-4-6",
) -> dict[str, object]:
    """claude -p CLI를 통해 스킬을 실행.

    Args:
        skill_body: SKILL.md 마크다운 본문 (system prompt)
        test_input: 사용자 입력 텍스트
        model: 사용할 모델

    Returns:
        {"output": str, "input_tokens": int, "output_tokens": int, "model": str}
        에러 시: {"output": "", "error": str, "input_tokens": 0, "output_tokens": 0, "model": str}
    """
    try:
        output = call_claude(prompt=test_input, model=model, system=skill_body)
        input_tokens = estimate_tokens(test_input + (skill_body or ""))
        output_tokens = estimate_tokens(output)
        return {
            "output": output,
            "input_tokens": input_tokens,
            "output_tokens": output_tokens,
            "model": model,
        }
    except Exception as e:
        return {
            "output": "",
            "error": str(e),
            "input_tokens": 0,
            "output_tokens": 0,
            "model": model,
        }
