import re
from typing import List, Dict, Any, Optional
from ..base import BaseRule, Diagnostic


class PairedPunctuationRule(BaseRule):
    rule_id = "paired-punctuation"
    severity = "error"
    PAIRS = {'(': ')', '[': ']', '{': '}', '《': '》', '"': '"', "'": "'"}

    def __init__(self, config: Optional[Dict[str, Any]] = None):
        super().__init__(config)

    def check(self, file_path: str, content: str) -> List[Diagnostic]:
        diagnostics = []
        lines = content.split('\n')

        for line_num, line in enumerate(lines, 1):
            stack = []
            for col_num, char in enumerate(line, 1):
                if char in self.PAIRS:
                    stack.append((char, col_num))
                elif char in self.PAIRS.values():
                    if not stack:
                        diagnostics.append(Diagnostic(file_path, line_num, col_num,
                                                      f"Unmatched closing punctuation '{char}'",
                                                      self.severity, self.rule_id))
                    else:
                        last_open, _ = stack.pop()
                        if self.PAIRS[last_open] != char:
                            diagnostics.append(Diagnostic(file_path, line_num, col_num,
                                                          f"Mismatched punctuation: expected '{self.PAIRS[last_open]}' but got '{char}'",
                                                          self.severity, self.rule_id))
            for open_char, col_num in stack:
                diagnostics.append(Diagnostic(file_path, line_num, col_num,
                                              f"Unclosed opening punctuation '{open_char}'",
                                              self.severity, self.rule_id))
        return diagnostics