import re

class PIIScrubber:
    def __init__(self):
        # Dictionary mapping placeholder prefixes to their regex patterns
        self.patterns = {
            'EMAIL': re.compile(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'),
            'PHONE': re.compile(r'\b(?:\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b'),
            'API_KEY': re.compile(r'\b(?:sk-[a-zA-Z0-9]{32,}|AKIA[0-9A-Z]{16}|gh[pousr]_[a-zA-Z0-9]{36})\b')
        }

    def anonymize(self, text: str) -> tuple[str, dict]:
        mapping = {}
        scrubbed_text = text
        counters = {k: 1 for k in self.patterns.keys()}
        
        for key, pattern in self.patterns.items():
            # Find unique matches in the current scrubbed text
            matches = set(pattern.findall(scrubbed_text))
            
            for match in matches:
                placeholder = f"<{key}_{counters[key]}>"
                mapping[placeholder] = match
                scrubbed_text = re.sub(re.escape(match), placeholder, scrubbed_text)
                counters[key] += 1
                
        return scrubbed_text, mapping

    def deanonymize(self, text: str, mapping: dict) -> str:
        deanonymized_text = text
        for placeholder, original in mapping.items():
            deanonymized_text = deanonymized_text.replace(placeholder, original)
        return deanonymized_text
