"""Code review tools for AI agent integration."""

import json
from langchain_core.tools import tool

from ieum.review import CodeReviewer, SecurityChecker, ReviewReporter


@tool
def review_code_tool(file_path: str) -> str:
    """Perform a comprehensive code review on a file.

    Analyzes code for:
    - Code quality issues
    - Potential bugs
    - Style violations
    - Complexity concerns
    - Security vulnerabilities

    Args:
        file_path: Path to the file to review.

    Returns:
        Markdown-formatted review report with issues and score.
    """
    reviewer = CodeReviewer()
    result = reviewer.review_file(file_path)

    reporter = ReviewReporter()
    report = reporter.generate_markdown(result)

    return report


@tool
def check_security_tool(code: str, language: str = "python") -> str:
    """Check code for security vulnerabilities.

    Detects common security issues including:
    - SQL injection
    - Command injection
    - XSS vulnerabilities
    - Hardcoded credentials
    - Buffer overflows (C/C++)
    - Unsafe functions

    Args:
        code: Source code to analyze.
        language: Programming language (python, cpp, c, mfc).

    Returns:
        JSON string containing detected security issues.
    """
    checker = SecurityChecker()
    issues = checker.check_code(code, language)

    if not issues:
        return json.dumps({
            "status": "clean",
            "message": "No security issues detected.",
            "issues": []
        }, indent=2)

    output = {
        "status": "issues_found",
        "count": len(issues),
        "issues": []
    }

    for issue in issues:
        output["issues"].append({
            "severity": issue.severity.value,
            "category": issue.category.value,
            "title": issue.title,
            "description": issue.description,
            "line": issue.line,
            "suggestion": issue.suggestion,
        })

    return json.dumps(output, indent=2, ensure_ascii=False)
