"""
Comment Checker Hook.

Warns when generated code contains excessive comments.
Code should be self-documenting; excessive comments indicate AI slop.
"""

import logging
from typing import Any

logger = logging.getLogger(__name__)

COMMENT_WARNING = """
[WARNING - EXCESSIVE COMMENTS DETECTED]

Your recent code edit contains a high ratio of comments ({ratio:.0%}).
Code generated by stravinsky should be indistinguishable from human-written code.

**Guidelines:**
- Comments should explain WHY, not WHAT
- Self-documenting code > commented code
- Remove obvious comments like "// Initialize the variable"
- Keep only: complex algorithms, security notes, performance optimizations, regex explanations

**Action Required:**
Review and remove unnecessary comments from your recent edit.
"""

COMMENT_PATTERNS = {
    "python": [
        r"^\s*#(?!\!)",
        r'^\s*"""[\s\S]*?"""',
        r"^\s*'''[\s\S]*?'''",
    ],
    "javascript": [
        r"^\s*//",
        r"/\*[\s\S]*?\*/",
    ],
    "typescript": [
        r"^\s*//",
        r"/\*[\s\S]*?\*/",
    ],
}

CODE_EXTENSIONS = {
    ".py": "python",
    ".js": "javascript",
    ".ts": "typescript",
    ".tsx": "typescript",
    ".jsx": "javascript",
}


async def comment_checker_hook(
    tool_name: str, arguments: dict[str, Any], output: str
) -> str | None:
    """
    Post-tool call hook that checks for excessive comments in code edits.
    """
    if tool_name not in ("Write", "Edit", "write", "edit"):
        return None

    file_path = arguments.get("filePath", arguments.get("file_path", ""))
    if not file_path:
        return None

    ext = None
    for extension in CODE_EXTENSIONS:
        if file_path.endswith(extension):
            ext = extension
            break

    if not ext:
        return None

    lang = CODE_EXTENSIONS[ext]
    content = arguments.get("content", arguments.get("newString", ""))

    if not content or len(content) < 50:
        return None

    comment_ratio = _calculate_comment_ratio(content, lang)

    if comment_ratio > 0.30:
        logger.warning(
            f"[CommentChecker] High comment ratio ({comment_ratio:.0%}) detected in {file_path}"
        )
        warning = COMMENT_WARNING.format(ratio=comment_ratio)
        return output + "\n" + warning

    return None


def _calculate_comment_ratio(content: str, lang: str) -> float:
    """Calculate the ratio of comment lines to total lines."""
    lines = content.split("\n")
    total_lines = len([l for l in lines if l.strip()])

    if total_lines == 0:
        return 0.0

    comment_lines = 0
    patterns = COMMENT_PATTERNS.get(lang, [])

    in_multiline = False
    for line in lines:
        stripped = line.strip()
        if not stripped:
            continue

        if lang == "python":
            if stripped.startswith("#") and not stripped.startswith("#!"):
                comment_lines += 1
            elif stripped.startswith('"""') or stripped.startswith("'''"):
                if stripped.count('"""') >= 2 or stripped.count("'''") >= 2:
                    comment_lines += 1
                else:
                    in_multiline = True
                    comment_lines += 1
            elif in_multiline:
                comment_lines += 1
                if '"""' in stripped or "'''" in stripped:
                    in_multiline = False
        else:
            if stripped.startswith("//"):
                comment_lines += 1
            elif stripped.startswith("/*"):
                in_multiline = True
                comment_lines += 1
            elif in_multiline:
                comment_lines += 1
                if "*/" in stripped:
                    in_multiline = False

    return comment_lines / total_lines
