"""Claude Code translation provider (uses Claude Agent SDK with subscription auth)."""

import asyncio
import json
import os

from transduck.providers.prompts import build_single_prompt, build_plural_single_prompt


def _ensure_token(config):
    token = os.environ.get(config.token_env)
    if not token:
        raise RuntimeError(
            f"Set {config.token_env} — run 'claude setup-token' to get your OAuth token"
        )


async def _translate_async(prompt):
    try:
        from claude_agent_sdk import query, ClaudeAgentOptions
    except ImportError:
        raise ImportError("Install the required package: pip install transduck[claude-code]")

    async for message in query(
        prompt=prompt,
        options=ClaudeAgentOptions(allowed_tools=[]),
    ):
        if hasattr(message, "result"):
            return message.result.strip()
    raise RuntimeError("No result from Claude Agent SDK")


def translate(source_text, source_lang, target_lang, project_context, string_context, config):
    """Translate a single string using Claude Code (Agent SDK)."""
    _ensure_token(config)
    prompt = build_single_prompt(source_text, source_lang, target_lang, project_context, string_context)
    return asyncio.run(_translate_async(prompt))


def translate_plural(one, other, source_lang, target_lang, project_context, string_context, config):
    """Translate plural forms using Claude Code (Agent SDK). Returns {category: translation}."""
    _ensure_token(config)
    prompt = build_plural_single_prompt(one, other, source_lang, target_lang, project_context, string_context)
    raw = asyncio.run(_translate_async(prompt))
    return json.loads(raw)
