"""
Crosstabs Analytics - Main analyzer class
"""

import requests
import pandas as pd
import io
from IPython.display import display, HTML
import json
from typing import Dict, Any, Optional, List


class CrosstabsAnalyzer:
    """
    AI-powered statistical analysis for Jupyter notebooks
    """
    
    def __init__(self, api_url: str = "https://api.crosstabs.com"):
        """
        Initialize Crosstabs Analyzer
        
        Args:
            api_url: Base URL for the Crosstabs API
        """
        self.api_url = api_url
        self.session = requests.Session()
    
    def analyze(self, df: pd.DataFrame, filename: str = "data.csv", **kwargs) -> HTML:
        """
        Analyze DataFrame with Crosstabs API
        
        Args:
            df: Pandas DataFrame to analyze
            filename: Name for the file
            **kwargs: Additional parameters for analysis
            
        Returns:
            HTML display of analysis results
        """
        # Save DataFrame to CSV in memory
        csv_buffer = io.StringIO()
        df.to_csv(csv_buffer, index=False)
        csv_data = csv_buffer.getvalue()
        
        # Create file-like object
        files = {'file': (filename, csv_data, 'text/csv')}
        
        # Call Crosstabs API
        response = self.session.post(f"{self.api_url}/chatgpt/analyze", files=files)
        
        if response.status_code == 200:
            result = response.json()
            return self._display_results(result)
        else:
            return HTML(f"<div style='color: red; padding: 20px; border: 1px solid red; border-radius: 8px;'>Error: {response.text}</div>")
    
    def get_raw_results(self, df: pd.DataFrame, filename: str = "data.csv") -> Dict[str, Any]:
        """
        Get raw analysis results as dictionary
        
        Args:
            df: Pandas DataFrame to analyze
            filename: Name for the file
            
        Returns:
            Dictionary with analysis results
        """
        # Save DataFrame to CSV in memory
        csv_buffer = io.StringIO()
        df.to_csv(csv_buffer, index=False)
        csv_data = csv_buffer.getvalue()
        
        # Create file-like object
        files = {'file': (filename, csv_data, 'text/csv')}
        
        # Call Crosstabs API
        response = self.session.post(f"{self.api_url}/chatgpt/analyze", files=files)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"API call failed: {response.text}")
    
    def batch_analyze(self, datasets: Dict[str, pd.DataFrame]) -> Dict[str, Dict[str, Any]]:
        """
        Analyze multiple datasets at once
        
        Args:
            datasets: Dictionary of dataset names and DataFrames
            
        Returns:
            Dictionary of analysis results for each dataset
        """
        results = {}
        
        for name, df in datasets.items():
            try:
                results[name] = self.get_raw_results(df, f"{name}.csv")
            except Exception as e:
                results[name] = {"error": str(e)}
        
        return results
    
    def export_pdf(self, analysis_id: str) -> str:
        """
        Export analysis results to PDF
        
        Args:
            analysis_id: ID of the analysis to export
            
        Returns:
            URL to the PDF report
        """
        return f"https://api.crosstabs.com/export/{analysis_id}?format=pdf"
    
    def export_excel(self, analysis_id: str) -> str:
        """
        Export analysis results to Excel
        
        Args:
            analysis_id: ID of the analysis to export
            
        Returns:
            URL to the Excel report
        """
        return f"https://api.crosstabs.com/export/{analysis_id}?format=excel"
    
    def export_json(self, analysis_id: str) -> str:
        """
        Export analysis results to JSON
        
        Args:
            analysis_id: ID of the analysis to export
            
        Returns:
            URL to the JSON data
        """
        return f"https://api.crosstabs.com/export/{analysis_id}?format=json"
    
    def _display_results(self, result: Dict[str, Any]) -> HTML:
        """
        Display analysis results in Jupyter
        
        Args:
            result: Analysis results from API
            
        Returns:
            HTML display of results
        """
        summary = result.get('summary', {})
        insights = result.get('key_insights', [])
        stats = result.get('statistical_tests', [])
        
        html = f"""
        <div style="padding: 20px; border: 1px solid #ddd; border-radius: 8px; background: #f9f9f9; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
            <h2 style="color: #2563eb; margin-top: 0;">📊 Crosstabs Analysis Results</h2>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0;">
                <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3 style="margin: 0; color: #2563eb;">Dataset</h3>
                    <p style="margin: 5px 0; font-size: 18px; font-weight: bold;">{summary.get('dataset_name', 'Unknown')}</p>
                </div>
                <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3 style="margin: 0; color: #2563eb;">Rows</h3>
                    <p style="margin: 5px 0; font-size: 18px; font-weight: bold;">{summary.get('total_rows', 0)}</p>
                </div>
                <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3 style="margin: 0; color: #2563eb;">Columns</h3>
                    <p style="margin: 5px 0; font-size: 18px; font-weight: bold;">{summary.get('total_columns', 0)}</p>
                </div>
                <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3 style="margin: 0; color: #2563eb;">Quality Score</h3>
                    <p style="margin: 5px 0; font-size: 18px; font-weight: bold; color: #2563eb;">{summary.get('data_quality_score', 0):.2f}</p>
                </div>
            </div>
            
            <h3 style="color: #2c3e50;">🔍 Key Insights</h3>
            <div style="margin: 15px 0;">
        """
        
        if insights:
            for i, insight in enumerate(insights, 1):
                confidence = insight.get('confidence', 0)
                html += f"""
                    <div style="background: white; padding: 15px; margin: 10px 0; border-radius: 6px; border-left: 4px solid #2563eb; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                        <strong>#{i}</strong> {insight.get('insight', 'No insight available')}
                        <br><small style="color: #666;">Confidence: {confidence:.0%}</small>
                        {insight.get('actionable', False) and '<span style="color: #28a745; font-weight: bold;"> ✅ Actionable</span>' or ''}
                    </div>
                """
        else:
            html += "<p>No insights available</p>"
        
        html += """
            </div>
            
            <h3 style="color: #2c3e50;">📈 Statistical Tests</h3>
            <div style="margin: 15px 0;">
        """
        
        if stats:
            for test in stats:
                significance = "✅ Significant" if test.get('significant', False) else "❌ Not significant"
                p_value = test.get('p_value', 0)
                html += f"""
                    <div style="background: #fff3cd; padding: 10px; margin: 5px 0; border-radius: 4px; border-left: 4px solid #ffc107;">
                        <strong>{test.get('test_name', 'Unknown Test')}</strong>: p = {p_value:.4f} {significance}
                    </div>
                """
        else:
            html += "<p>No statistical tests available</p>"
        
        html += """
            </div>
            
            <div style="margin-top: 30px; padding: 20px; background: #e3f2fd; border-radius: 8px; text-align: center;">
                <p><strong>Want to share these results?</strong></p>
                <p>Visit <a href="https://crosstabs.com" target="_blank">crosstabs.com</a> for more analysis tools and features.</p>
            </div>
        </div>
        """
        
        return HTML(html)
