import datetime
import logging
import os
import random
import time
from typing import List, Dict, Any

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Dummy data generation functions (replace with actual database queries)
def generate_dummy_cost_data_by_provider() -> Dict[str, float]:
    """Generates dummy cost data by provider."""
    providers = ["AWS", "Azure", "GCP", "Other"]
    return {provider: round(random.uniform(100, 1000), 2) for provider in providers}

def generate_dummy_cost_data_by_day(days: int = 30) -> Dict[str, float]:
    """Generates dummy cost data by day for the last 'days' days."""
    today = datetime.date.today()
    data = {}
    for i in range(days):
        date = today - datetime.timedelta(days=i)
        data[date.strftime("%Y-%m-%d")] = round(random.uniform(50, 300), 2)
    return data

def generate_dummy_top_costs(num_costs: int = 5) -> List[Dict[str, Any]]:
    """Generates dummy top costs."""
    costs = []
    for i in range(num_costs):
        costs.append({
            "resource": f"Resource-{i+1}",
            "cost": round(random.uniform(20, 500), 2),
            "provider": random.choice(["AWS", "Azure", "GCP"])
        })
    return costs

class DashboardGenerator:
    """
    Generates a static HTML dashboard showing cost breakdown using dummy data.
    """

    def __init__(self, output_file: str = "/mnt/e/genesis-system/apps/dashboard/cost_dashboard.html"):
        """
        Initializes the DashboardGenerator with the output file path.

        Args:
            output_file: The path to the HTML file to be generated.
        """
        self.output_file = output_file
        self.logger = logging.getLogger(__name__)  # Use class-specific logger

    def generate_html(self) -> None:
        """
        Generates the HTML content for the cost dashboard using dummy data and saves it to the output file.
        """
        try:
            cost_data_by_provider = generate_dummy_cost_data_by_provider()
            cost_data_by_day = generate_dummy_cost_data_by_day()
            top_costs = generate_dummy_top_costs()

            html_content = self._build_html(cost_data_by_provider, cost_data_by_day, top_costs)

            with open(self.output_file, "w") as f:
                f.write(html_content)

            self.logger.info(f"Dashboard generated successfully at {self.output_file}")

        except Exception as e:
            self.logger.error(f"Error generating dashboard: {e}", exc_info=True)
            raise

    def _build_html(self, cost_data_by_provider: Dict[str, float], cost_data_by_day: Dict[str, float], top_costs: List[Dict[str, Any]]) -> str:
        """
        Builds the HTML content for the dashboard.

        Args:
            cost_data_by_provider: Cost data by provider.
            cost_data_by_day: Cost data by day.
            top_costs: A list of top costs.

        Returns:
            The HTML content as a string.
        """
        html = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Cost Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 20px;
        }}
        .container {{
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
        }}
        .chart-container {{
            width: 45%;
            margin-bottom: 20px;
        }}
        table {{
            border-collapse: collapse;
            width: 100%;
        }}
        th, td {{
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }}
        th {{
            background-color: #f2f2f2;
        }}
    </style>
    <meta http-equiv="refresh" content="300">
</head>
<body>
    <h1>Cost Dashboard</h1>
    <div class="container">
        <div class="chart-container">
            <h2>Cost by Provider</h2>
            <canvas id="providerChart"></canvas>
        </div>
        <div class="chart-container">
            <h2>Cost by Day</h2>
            <canvas id="dailyChart"></canvas>
        </div>
    </div>
    <div>
        <h2>Top Costs</h2>
        <table>
            <thead>
                <tr>
                    <th>Resource</th>
                    <th>Cost</th>
                    <th>Provider</th>
                </tr>
            </thead>
            <tbody>
                {''.join(f'<tr><td>{cost["resource"]}</td><td>{cost["cost"]}</td><td>{cost["provider"]}</td></tr>' for cost in top_costs)}
            </tbody>
        </table>
    </div>

    <script>
        // Provider Chart
        const providerData = {
            labels: {list(cost_data_by_provider.keys())},
            datasets: [{{
                label: 'Cost',
                data: {list(cost_data_by_provider.values())},
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)'
                ],
                borderWidth: 1
            }}]
        };

        const providerConfig = {{
            type: 'pie',
            data: providerData,
            options: {{
                responsive: true,
                maintainAspectRatio: false,
            }}
        }};

        const providerChart = new Chart(
            document.getElementById('providerChart'),
            providerConfig
        );

        // Daily Chart
        const dailyData = {{
            labels: {list(cost_data_by_day.keys())},
            datasets: [{{
                label: 'Cost',
                data: {list(cost_data_by_day.values())},
                borderColor: 'rgb(75, 192, 192)',
                tension: 0.1
            }}]
        }};

        const dailyConfig = {{
            type: 'line',
            data: dailyData,
            options: {{
                responsive: true,
                maintainAspectRatio: false,
            }}
        }};

        const dailyChart = new Chart(
            document.getElementById('dailyChart'),
            dailyConfig
        );
    </script>
</body>
</html>
"""
        return html

# Example usage (for testing)
if __name__ == "__main__":
    generator = DashboardGenerator()
    generator.generate_html()


