"""
scientific_utilities.py

Minimal utilities for scientific validation and report generation
"""

import pandas as pd
import numpy as np
import base64
import io
import matplotlib.pyplot as plt
from typing import Dict, Any, Optional


class ScientificValidator:
    """Minimal scientific data validator"""

    def validate_experimental_data(
        self, data: pd.DataFrame, params_config: Dict, responses_config: Dict
    ) -> Dict[str, Any]:
        """Validate experimental data"""
        try:
            validation_report = {
                "valid": True,
                "warnings": [],
                "errors": [],
                "data_quality": "Good",
                "n_experiments": len(data),
                "completeness": 1.0,
            }

            # Basic validation
            if data.empty:
                validation_report["valid"] = False
                validation_report["errors"].append("No experimental data provided")
                return validation_report

            # Check for required columns
            missing_params = [p for p in params_config.keys() if p not in data.columns]
            missing_responses = [
                r for r in responses_config.keys() if r not in data.columns
            ]

            if missing_params:
                validation_report["warnings"].append(
                    f"Missing parameters: {missing_params}"
                )
            if missing_responses:
                validation_report["warnings"].append(
                    f"Missing responses: {missing_responses}"
                )

            # Check for NaN values
            nan_count = data.isnull().sum().sum()
            if nan_count > 0:
                validation_report["warnings"].append(f"Found {nan_count} NaN values")
                validation_report["completeness"] = 1.0 - (
                    nan_count / (len(data) * len(data.columns))
                )

            return validation_report

        except Exception as e:
            return {
                "valid": False,
                "errors": [f"Validation failed: {str(e)}"],
                "warnings": [],
                "data_quality": "Poor",
                "n_experiments": 0,
                "completeness": 0.0,
            }


class ReportGenerator:
    """Minimal report generator"""

    def _fig_to_base64(self, fig) -> str:
        """Convert matplotlib figure to base64 string"""
        try:
            buffer = io.BytesIO()
            fig.savefig(buffer, format="png", bbox_inches="tight", dpi=100)
            buffer.seek(0)
            image_png = buffer.getvalue()
            buffer.close()
            graphic = base64.b64encode(image_png)
            return graphic.decode("utf-8")
        except Exception:
            return ""

    def generate_report(self, data: Dict[str, Any], format: str = "markdown") -> str:
        """Generate a basic report"""
        try:
            report = f"""# Optimization Report

## Summary
- Experiments: {data.get('n_experiments', 'N/A')}
- Status: {data.get('status', 'N/A')}
- Generated: {data.get('timestamp', 'N/A')}

## Results
{data.get('summary', 'No summary available')}

## Data Quality
- Validation: {data.get('validation_status', 'N/A')}
- Completeness: {data.get('completeness', 'N/A')}

---
Generated by Multi-Objective Optimization Laboratory
"""
            return report
        except Exception:
            return "# Report Generation Failed\n\nUnable to generate report due to data issues."


# Create global instances
scientific_validator = ScientificValidator()
report_generator = ReportGenerator()
