"""
BSS Skill: Diff Parser
Parses git diff / unified diff format from a PR review prompt.
Outputs structured metadata: changed files, hunk contexts, additions/deletions,
and modified function/class signatures.
"""
import re

text = PROMPT  # noqa: F821

files_changed: list = []
hunks: list = []
additions = 0
deletions = 0
current_file = None

for line in text.splitlines():
    # New file in diff
    if line.startswith("+++ b/"):
        current_file = line[6:].strip()
        if current_file not in files_changed:
            files_changed.append(current_file)
    elif line.startswith("diff --git"):
        match = re.search(r"b/(.+)$", line)
        if match:
            current_file = match.group(1).strip()
            if current_file not in files_changed:
                files_changed.append(current_file)
    # Hunk headers
    elif line.startswith("@@"):
        ctx_match = re.search(r"@@ .+? @@ ?(.*)", line)
        ctx = ctx_match.group(1).strip()[:60] if ctx_match else ""
        hunks.append({"file": current_file or "?", "ctx": ctx})
    # Count changes (skip file markers)
    elif line.startswith("+") and not line.startswith("+++"):
        additions += 1
    elif line.startswith("-") and not line.startswith("---"):
        deletions += 1

# Function/class signatures that were added or removed
func_changes = re.findall(
    r"^[+\-][ \t]*(?:def|async def|function|class|public|private|protected)\s+\w+[^{;\n]*",
    text, re.MULTILINE,
)
func_changes = [f.strip()[:80] for f in func_changes[:12]]

# Fallback: no diff markers found — treat as plain PR description
if not files_changed and not additions:
    desc_lines = [l.strip() for l in text.splitlines() if l.strip()][:30]
    print("DIFF_FORMAT:plain")
    print(f"DESCRIPTION_LINES:{len(desc_lines)}")
    for dl in desc_lines:
        print(f"  {dl}")
else:
    print(f"DIFF_FORMAT:unified")
    print(f"FILES_CHANGED:{len(files_changed)}")
    for f in files_changed[:8]:
        print(f"  {f}")
    print(f"STATS:+{additions} -{deletions} lines in {len(hunks)} hunks")
    if func_changes:
        print(f"FUNCTIONS:{len(func_changes)}")
        for fc in func_changes[:8]:
            print(f"  {fc}")
    if hunks:
        print(f"HUNKS:{len(hunks)}")
        for h in hunks[:6]:
            print(f"  [{h['file']}] {h['ctx']}")
