"""
Model Builder
=============

This module provides utilities for building machine learning models
for sentiment analysis.
"""

import logging
from typing import Dict, Any
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC

from src.data_preparation.src.data_cleaner import TextCleaner

logger = logging.getLogger(__name__)


class ModelBuilder:
    """
    Builds machine learning pipelines for sentiment analysis.
    """
    
    DEFAULT_PARAMS = {
        "use_spacy_lemma": False,
        "c_value": 1.0,
        "min_df": 5,
        "max_df": 0.9,
        "ngram_max": 2,
        "max_features": None,
        "stop_words": "english"
    }
    
    def __init__(self, **kwargs):
        """
        Initialize the model builder with hyperparameters.
        
        Args:
            **kwargs: Hyperparameters for the model (see DEFAULT_PARAMS)
        """
        self.params = {**self.DEFAULT_PARAMS, **kwargs}
        logger.info(f"ModelBuilder initialized with params: {self.params}")
    
    def build_tfidf_svm_pipeline(self) -> Pipeline:
        """
        Build a TF-IDF + LinearSVC pipeline.
        
        Returns:
            Scikit-learn Pipeline
        """
        logger.info("Building TF-IDF + LinearSVC pipeline...")
        
        pipeline = Pipeline([
            ("clean", TextCleaner(use_spacy_lemma=self.params["use_spacy_lemma"])),
            ("tfidf", TfidfVectorizer(
                ngram_range=(1, self.params["ngram_max"]),
                min_df=self.params["min_df"],
                max_df=self.params["max_df"],
                max_features=self.params["max_features"],
                sublinear_tf=True,
                strip_accents=None,
                dtype=np.float32,
                stop_words=self.params["stop_words"]
            )),
            ("clf", LinearSVC(
                C=self.params["c_value"],
                max_iter=10000,
                random_state=42
            ))
        ])
        
        logger.info("Pipeline built successfully")
        return pipeline
    
    def get_model_info(self) -> Dict[str, Any]:
        """
        Get information about the model configuration.
        
        Returns:
            Dictionary with model information
        """
        return {
            "model_type": "TF-IDF + LinearSVC",
            "parameters": self.params,
            "components": [
                "TextCleaner",
                "TfidfVectorizer",
                "LinearSVC"
            ]
        }


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    
    # Example usage
    builder = ModelBuilder(
        c_value=1.0,
        min_df=5,
        max_df=0.9,
        ngram_max=2
    )
    
    model = builder.build_tfidf_svm_pipeline()
    print("\nModel Pipeline:")
    print(model)
    
    print("\nModel Info:")
    print(builder.get_model_info())
