"""Code review skill — analyzes code snippets for issues.

This is an example OpenClaw skill that demonstrates how operon-guard
can verify skill behavior before deployment.
"""

import re


def run(code_or_question: str) -> str:
    """Review code or answer code-related questions.

    This is the entry point that OpenClaw calls when the skill is invoked.
    """
    text = code_or_question.strip()

    if not text:
        return "Please provide a code snippet or question for review."

    # detect if it's a question vs code
    if text.endswith("?") or text.lower().startswith(("what", "how", "why", "can", "should")):
        return _answer_question(text)

    return _review_code(text)


def _review_code(code: str) -> str:
    """Analyze code for common issues."""
    issues = []

    # security checks
    if re.search(r'(password|secret|api_key|token)\s*=\s*["\'][^"\']+["\']', code, re.I):
        issues.append("[SECURITY] Hardcoded credential detected. Use environment variables instead.")

    if re.search(r'eval\s*\(', code):
        issues.append("[SECURITY] Use of eval() detected. This is a code injection risk.")

    if re.search(r'exec\s*\(', code):
        issues.append("[SECURITY] Use of exec() detected. This is a code injection risk.")

    if re.search(r'SELECT.*\+.*input|f"SELECT.*\{', code, re.I):
        issues.append("[SECURITY] Possible SQL injection. Use parameterized queries.")

    if re.search(r'innerHTML\s*=', code):
        issues.append("[SECURITY] Direct innerHTML assignment. Risk of XSS. Use textContent or sanitize input.")

    # performance checks
    if re.search(r'for.*in.*:\s*\n\s*.*\.query\(|for.*in.*:\s*\n\s*.*\.execute\(', code):
        issues.append("[PERFORMANCE] Possible N+1 query pattern. Consider batch loading.")

    if re.search(r'import\s+\*', code):
        issues.append("[STYLE] Wildcard import detected. Import specific names instead.")

    # best practices
    if re.search(r'except\s*:', code):
        issues.append("[STYLE] Bare except clause. Catch specific exceptions.")

    if re.search(r'# TODO|# FIXME|# HACK', code, re.I):
        issues.append("[INFO] TODO/FIXME comment found. Consider addressing before deployment.")

    if not issues:
        return "Code review complete. No issues found. The code looks clean."

    header = f"Code review complete. Found {len(issues)} issue(s):\n\n"
    return header + "\n".join(f"  {i+1}. {issue}" for i, issue in enumerate(issues))


def _answer_question(question: str) -> str:
    """Answer code-related questions."""
    q = question.lower()

    if "sql injection" in q:
        return (
            "SQL injection occurs when user input is directly concatenated into SQL queries. "
            "Prevention: Use parameterized queries (prepared statements), ORMs, "
            "and input validation. Never use string concatenation for SQL."
        )

    if "xss" in q or "cross-site" in q:
        return (
            "Cross-Site Scripting (XSS) happens when untrusted data is rendered in HTML. "
            "Prevention: Sanitize all user input, use textContent instead of innerHTML, "
            "implement Content Security Policy headers, and use templating engines with auto-escaping."
        )

    if "best practice" in q:
        return (
            "Key code review best practices: "
            "1) Check for hardcoded secrets, "
            "2) Verify input validation, "
            "3) Look for SQL injection and XSS, "
            "4) Check error handling specificity, "
            "5) Review for N+1 query patterns, "
            "6) Ensure proper logging without PII."
        )

    return (
        f"I can help with code review questions. "
        f"You asked: '{question[:100]}'. "
        f"For a detailed review, paste your code directly."
    )
