#!/usr/bin/env python3
"""aria-code-bulk — DeepSeek-Coder Helper für Code-Bulk-Tasks (Phase 2 Helper-LLM).

Use-Cases:
- Boilerplate-Generation (CRUD, Test-Stubs)
- Translation zwischen Sprachen / Frameworks
- Code-Cleanup / Reformatting
- Bulk-Refactoring mit klaren Patterns

KOSTEN: deepseek-v4-pro ist ~10x günstiger als Opus für Code. Default-Modell.

CLI:
    python3 aria-code-bulk.py "Generate Python dataclass for User with id, name, email" \\
        --language python --max-tokens 500
    python3 aria-code-bulk.py "Convert this jest test to vitest:" \\
        --context-file test.js --pro
    cat snippet.py | python3 aria-code-bulk.py "Add type hints to this function" --stdin

Output: rohe Antwort (Code + ggf. Kommentare). Use `--code-only` für nur Code-Block-Inhalt.
"""
from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

sys.path.insert(0, "/root/aria/scripts")
from aria_llm_providers import complete  # noqa: E402

DEFAULT_MODEL_FLASH = "deepseek-v4-flash"
DEFAULT_MODEL_PRO = "deepseek-v4-pro"


SYSTEM_PROMPT = """You are a senior software engineer doing code-bulk work for Aria.
Be precise and minimal. Output:
1. Code in a single ```<lang> ... ``` block, no surrounding prose unless the user asks for an explanation.
2. If multiple files: separate blocks with file-path comments.
3. Type-hints + docstrings where the language supports it.
4. No placeholders like "TODO" — produce working code.
5. If the task is impossible without more info, output one line starting with "QUESTION:" and stop.
"""


CODE_BLOCK_RE = re.compile(r"```(?:\w+)?\n(.*?)```", re.DOTALL)


def _extract_code(text: str) -> str:
    matches = CODE_BLOCK_RE.findall(text)
    if matches:
        return "\n\n".join(m.strip() for m in matches)
    return text.strip()


def main() -> int:
    parser = argparse.ArgumentParser(description="Aria Code-Bulk via DeepSeek (Phase 2)")
    parser.add_argument("task", nargs="?", help="task description (or use --stdin)")
    parser.add_argument("--language", "--lang", default="python", help="target language (hint)")
    parser.add_argument("--context-file", action="append", default=[],
                        help="file path to include as context (multiple allowed)")
    parser.add_argument("--stdin", action="store_true", help="read additional context from stdin")
    parser.add_argument("--pro", action="store_true",
                        help="use deepseek-v4-pro (default: v4-flash, 4× cheaper)")
    parser.add_argument("--max-tokens", type=int, default=2000)
    parser.add_argument("--code-only", action="store_true",
                        help="extract code from ``` blocks, drop prose")
    parser.add_argument("--json", action="store_true", help="emit full result-dict as JSON")
    args = parser.parse_args()

    parts = []
    if args.task:
        parts.append(f"Task:\n{args.task}")
    if args.context_file:
        for f in args.context_file:
            try:
                content = Path(f).read_text(encoding="utf-8", errors="replace")
                parts.append(f"Context file `{f}`:\n```{args.language}\n{content}\n```")
            except OSError as exc:
                print(f"ERROR reading {f}: {exc}", file=sys.stderr)
                return 1
    if args.stdin:
        stdin_text = sys.stdin.read()
        if stdin_text.strip():
            parts.append(f"Stdin context:\n```{args.language}\n{stdin_text}\n```")
    if not parts:
        parser.error("provide task and/or --context-file and/or --stdin")

    prompt = SYSTEM_PROMPT + "\n\n" + "\n\n".join(parts) + f"\n\nLanguage hint: {args.language}"

    model = DEFAULT_MODEL_PRO if args.pro else DEFAULT_MODEL_FLASH
    out = complete(provider="deepseek", model=model,
                    prompt=prompt, max_tokens=args.max_tokens,
                    task_class="code-bulk")

    if args.json:
        import json
        print(json.dumps(out, ensure_ascii=False, indent=2)[:8000])
        return 0
    text = out["text"]
    if args.code_only:
        text = _extract_code(text)
    print(text)
    sys.stderr.write(
        f"[code-bulk] {model} · tokens {out['prompt_tokens']}/{out['completion_tokens']} "
        f"· cost ${out['cost_usd']:.6f} · {out['latency_ms']}ms\n"
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
