"""
BSS Skill: Code Review Condenser
Parses a code diff or raw code snippet and outputs a compact structural
summary: changed files, functions, line stats, and added/removed imports.
The LLM gets the shape of the change without re-reading every line.
"""
import re
import collections

text = PROMPT

# ── Detect mode: unified diff vs raw code ────────────────────────────────────
is_diff = bool(re.search(r"^(?:diff --git|@@\s+-\d|^---\s+a/|^\+\+\+\s+b/)", text, re.MULTILINE))

if is_diff:
    # ── Parse unified diff ────────────────────────────────────────────────────
    changed_files = re.findall(r"^(?:---|\+\+\+)\s+[ab]/(.+)", text, re.MULTILINE)
    changed_files = list(dict.fromkeys(
        f for f in changed_files if not f.startswith("/dev/null")
    ))

    hunks = re.findall(r"^@@[^@@]+@@", text, re.MULTILINE)

    added_lines   = [l[1:] for l in text.splitlines() if l.startswith("+") and not l.startswith("+++")]
    removed_lines = [l[1:] for l in text.splitlines() if l.startswith("-") and not l.startswith("---")]

    # Functions / methods touched
    func_pattern = re.compile(
        r"^[+\-]\s*(?:def |async def |function |func |public |private |protected |"
        r"static |class |const |let |var )\s*(\w+)"
    )
    touched_funcs = []
    for line in text.splitlines():
        m = func_pattern.match(line)
        if m:
            touched_funcs.append(("+" if line.startswith("+") else "-", m.group(1)))

    # Added/removed imports
    added_imports   = [l.strip() for l in added_lines   if re.match(r"\s*(import|from|require|use )", l)]
    removed_imports = [l.strip() for l in removed_lines if re.match(r"\s*(import|from|require|use )", l)]

    print("=== BIBIVIDI DIFF SUMMARY ===")
    if changed_files:
        print(f"Files changed ({len(changed_files)}): {', '.join(changed_files[:10])}")
    print(f"Hunks: {len(hunks)} | +{len(added_lines)} lines / -{len(removed_lines)} lines")

    if touched_funcs:
        print(f"\nTouched symbols:")
        for sign, name in touched_funcs[:15]:
            print(f"  {sign} {name}()")

    if added_imports:
        print(f"\nNew imports ({len(added_imports)}):")
        for imp in added_imports[:8]:
            print(f"  + {imp[:100]}")
    if removed_imports:
        print(f"Removed imports ({len(removed_imports)}):")
        for imp in removed_imports[:8]:
            print(f"  - {imp[:100]}")

else:
    # ── Parse raw code snippet ────────────────────────────────────────────────
    lines = text.splitlines()

    # Detect language heuristic
    lang = "unknown"
    if re.search(r"def |import |class |:\s*$", text):
        lang = "Python"
    elif re.search(r"function |const |let |var |=>", text):
        lang = "JavaScript/TypeScript"
    elif re.search(r"pub fn |fn |impl |use std::", text):
        lang = "Rust"
    elif re.search(r"func |package |:= ", text):
        lang = "Go"

    # Top-level definitions
    func_names = re.findall(
        r"^\s*(?:async\s+)?(?:def|function|func|pub fn|fn)\s+(\w+)",
        text, re.MULTILINE
    )
    class_names = re.findall(r"^\s*(?:class|struct|interface|enum)\s+(\w+)", text, re.MULTILINE)
    imports = [l.strip() for l in lines if re.match(r"\s*(import|from|require|use |#include)", l)]

    # Complexity heuristic: branches
    branch_count = len(re.findall(r"\b(if|elif|else|for|while|match|switch|try|except|catch)\b", text))

    # Extract any user instruction outside code fences
    no_code = re.sub(r"```.*?```", "", text, flags=re.DOTALL).strip()
    task = no_code[:300].strip() if no_code else ""

    print("=== BIBIVIDI CODE SUMMARY ===")
    print(f"Language: {lang} | Lines: {len(lines)} | Branches: {branch_count}")

    if class_names:
        print(f"Classes/Structs: {', '.join(class_names[:10])}")
    if func_names:
        print(f"Functions ({len(func_names)}): {', '.join(func_names[:15])}")
    if imports:
        print(f"Imports ({len(imports)}): {', '.join(imp[:60] for imp in imports[:8])}")

    # First docstring / comment block
    doc = re.search(r'(?:"""|\'\'\')(.*?)(?:"""|\'\'\')|(#[^\n]+(?:\n#[^\n]+){0,4})', text, re.DOTALL)
    if doc:
        snippet = (doc.group(1) or doc.group(2) or "").strip()[:200]
        if snippet:
            print(f"Doc/comments: {snippet}")

    if task:
        print(f"\nUser request: {task}")

# ── Shared footer ─────────────────────────────────────────────────────────────
print(f"\n(Condensed from {len(text)} chars by BIBIVIDI)")
print("=== END CODE SUMMARY ===")
