import re

class CAIO:
    def __init__(self, model="gemini-1.5-flash"):
        self.model = model
        self.developer = "Atharva"
        
        # Generalized NLP Patterns
        self.noise_categories = {
            "greetings": r"(?i)^(hello|hi|hey|greetings|dear|good (morning|afternoon|evening)).*?[!.]",
            "politeness": r"(?i)(please|kindly|thank you|thanks|hope you are doing well|have a (great|good) day)[!.]?",
            "introductions": r"(?i)(i am|i'm) (a student|learning|working on|new to).*?[!.]",
            "requests": r"(?i)(can you|could you|i (really )?need|help me with|look at).*?[?.]",
            "praise": r"(?i)(you are|best|great|awesome) (ai|assistant|model)[!.]?"
        }

    def _scrub_conversational_noise(self, text):
        """Generalizes cleaning by removing entire sentences of fluff."""
        # Split text into sentences to avoid over-scrubbing mid-code
        sentences = re.split(r'(?<=[.!?]) +', text)
        clean_sentences = []

        for sentence in sentences:
            is_noise = False
            for pattern in self.noise_categories.values():
                if re.search(pattern, sentence):
                    is_noise = True
                    break
            
            # Keep the sentence only if it doesn't match noise or looks like code
            if not is_noise or any(c in sentence for c in ['=', 'def ', 'class ', 'import ']):
                clean_sentences.append(sentence)
        
        return " ".join(clean_sentences).strip()

    def optimize(self, prompt, tier="dev"):
        # Step 1: Broad NLP scrubbing
        clean_prompt = self._scrub_conversational_noise(prompt)
        
        # Step 2: Code minification
        minified = re.sub(r'#.*', '', clean_prompt)
        # Remove extra whitespaces/newlines
        minified = re.sub(r'\s+', ' ', minified).strip()
        
        if tier == "dev":
            final_prompt = f"CODE-ONLY;NO-CHAT;MINIFY-RESPONSE: {minified}"
        else:
            final_prompt = minified

        tokens_saved = len(prompt) - len(final_prompt)
        
        return {
            "optimized_prompt": final_prompt,
            "tokens_saved": tokens_saved,
            "model": self.model,
            "engine_by": self.developer
        }