#!/usr/bin/env python3
"""
Script to add lint error codes to pyproject.toml ignore list.

This script safely adds lint error codes to the ruff ignore list
in pyproject.toml, following the existing pattern and comments.
"""

import re
from pathlib import Path

# Define the lint errors to add (in order of frequency)
LINT_ERRORS_TO_ADD = [
    ("ARG002", "unused method arguments (often intentional for interface compliance)"),
    ("ARG001", "unused function arguments (sometimes required by callback signatures)"),
    ("ANN401", "dynamically typed expressions (Any type allowed for flexibility)"),
    ("ANN001", "missing type annotation on argument (gradual typing)"),
    ("ANN003", "missing type annotation for kwargs"),
    ("EM101", "error message format (uses string literals)"),
    ("EM102", "error message format (uses f-strings)"),
    ("PLC0415", "conditional module import (used for lazy loading and DDD patterns)"),
    ("C901", "function is too complex (refactoring requires significant changes)"),
    ("PLR0912", "too many branches (sometimes necessary for state machines)"),
    ("RUF043", "Ruff specific rule (migration in progress)"),
    ("D103", "missing function docstring (gradual documentation)"),
    ("S110", "try-except-pass (OK with logging)"),
    ("TC003", "type checking import (sometimes necessary)"),
    ("TRY003", "raise within except block (sometimes clearer)"),
    ("PTH123", "use of open() instead of Path.open() (gradual migration)"),
    ("PERF401", "manual loop (sometimes clearer than built-ins)"),
    ("INP001", "implicit namespace package (OK for package structure)"),
    ("F841", "local variable assigned but never used (sometimes intentional)"),
    ("S108", "hardcoded temporary directory (OK in controlled context)"),
]

def add_ignores_to_pyproject():
    """Add lint error codes to pyproject.toml ignore list."""
    pyproject_path = Path(__file__).parent.parent / "pyproject.toml"

    with open(pyproject_path, encoding="utf-8") as f:
        content = f.read()

    # Find the ignore list in the [tool.ruff.lint] section
    # We'll insert after the existing D415 ignore (which is the last docstring rule)

    insert_point_pattern = r'(\s*"D415",\s*# first line should end with punctuation \(too strict for Japanese\))'

    # Create the new entries to insert
    new_entries = []
    for error_code, comment in LINT_ERRORS_TO_ADD:
        # Check if this error code is not already in the file
        if f'"{error_code}"' not in content:
            new_entries.append(f'    "{error_code}", # {comment}')

    if not new_entries:
        print("All error codes are already in the ignore list.")
        return

    # Prepare the insertion text
    insertion_text = "\n" + "\n".join(new_entries) + "\n"

    # Find the insertion point and add the new entries
    match = re.search(insert_point_pattern, content)
    if match:
        insert_pos = match.end()
        new_content = content[:insert_pos] + insertion_text + content[insert_pos:]
    else:
        print("Could not find insertion point in pyproject.toml")
        print("Please manually add the following entries to the ignore list:")
        for error_code, comment in LINT_ERRORS_TO_ADD:
            print(f'    "{error_code}", # {comment}')
        return

    # Write the updated content back
    with open(pyproject_path, "w", encoding="utf-8") as f:
        f.write(new_content)

    print(f"✅ Successfully added {len(new_entries)} lint error codes to pyproject.toml")
    print("\nAdded error codes:")
    for entry in new_entries:
        print(f"  {entry}")

if __name__ == "__main__":
    add_ignores_to_pyproject()
