"""
Business Goals and Objectives
==============================

This module defines the business goals, success criteria, and project objectives
for the Sentiment140 sentiment analysis project.
"""

import json
import logging
from pathlib import Path
from typing import Any, Dict

logger = logging.getLogger(__name__)


class BusinessGoals:
    """
    Defines and manages business goals for the sentiment analysis project.
    """

    def __init__(self):
        self.objectives = {
            "primary": "Develop a sentiment analysis model for Twitter data",
            "accuracy_target": 0.75,
            "f1_score_target": 0.75,
            "deployment_target": "production-ready API",
            "scalability": "Handle 1000+ requests per minute",
        }

        self.success_criteria = {
            "model_performance": {
                "min_accuracy": 0.75,
                "min_macro_f1": 0.75,
                "max_inference_time_ms": 100,
            },
            "business_impact": {
                "api_availability": 0.99,
                "response_time_p95_ms": 200,
                "scalability_target_rps": 1000,
            },
        }

    def get_objectives(self) -> Dict[str, Any]:
        """Return business objectives."""
        return self.objectives

    def get_success_criteria(self) -> Dict[str, Any]:
        """Return success criteria."""
        return self.success_criteria

    def validate_model_performance(self, accuracy: float, macro_f1: float) -> bool:
        """
        Validate if model meets business requirements.

        Args:
            accuracy: Model accuracy score
            macro_f1: Model macro F1 score

        Returns:
            True if model meets requirements, False otherwise
        """
        criteria = self.success_criteria["model_performance"]

        meets_accuracy = accuracy >= criteria["min_accuracy"]
        meets_f1 = macro_f1 >= criteria["min_macro_f1"]

        if meets_accuracy and meets_f1:
            logger.info(
                f"✓ Model meets business requirements: Accuracy={accuracy:.4f}, F1={macro_f1:.4f}"
            )
            return True
        else:
            logger.warning(
                f"✗ Model does not meet requirements: Accuracy={accuracy:.4f}, F1={macro_f1:.4f}"
            )
            return False

    def save_goals(self, output_path: Path):
        """Save business goals to JSON file."""
        goals_data = {
            "objectives": self.objectives,
            "success_criteria": self.success_criteria,
        }

        output_path.parent.mkdir(parents=True, exist_ok=True)
        with open(output_path, "w", encoding="utf-8") as f:
            json.dump(goals_data, f, indent=2, ensure_ascii=False)

        logger.info(f"Business goals saved to {output_path}")

    def generate_report(self) -> str:
        """Generate a business understanding report."""
        report = """
# Business Understanding Report
## Sentiment Analysis on Twitter Data (Sentiment140)

### Business Objectives
- Primary Goal: Develop a production-ready sentiment analysis model for Twitter data
- Target Accuracy: ≥ 75%
- Target Macro F1-Score: ≥ 75%
- Deployment: REST API with high availability
- Scalability: Handle 1000+ requests per minute

### Success Criteria

#### Model Performance
- Minimum Accuracy: 75%
- Minimum Macro F1: 75%
- Maximum Inference Time: 100ms

#### Business Impact
- API Availability: 99%+
- Response Time (P95): < 200ms
- Scalability Target: 1000 RPS

### Use Cases
1. **Social Media Monitoring**: Real-time sentiment analysis for brand monitoring
2. **Customer Service**: Automatic classification of customer feedback
3. **Market Research**: Understand public opinion on products/services
4. **Crisis Detection**: Early warning system for negative sentiment trends

### Risks and Constraints
- Data quality and representativeness
- Model bias and fairness considerations
- Scalability and infrastructure costs
- Maintenance and model drift over time
        """
        return report


if __name__ == "__main__":
    # Example usage
    logging.basicConfig(level=logging.INFO)

    goals = BusinessGoals()
    print(goals.generate_report())

    # Validate sample model performance
    goals.validate_model_performance(accuracy=0.78, macro_f1=0.76)
