import math
import json
from datetime import datetime

class BifacialSolarSimulation:
    def __init__(self):
        # Panel specifications (Hanersun N-TOPCon 700W)
        self.panel_power = 700  # watts
        self.panel_efficiency = 0.225  # 22.5%
        self.bifaciality_factor = 0.80  # Average of 75-85%
        self.panel_area = 2.384 * 1.303  # m²
        
        # Location: Lago Brown, Chile
        self.latitude = -47.3919449
        self.longitude = -72.3174973
        self.elevation = 165  # meters
        
        # IDEAL CONDITIONS - no weather effects, clear skies
        self.monthly_ghi = {
            1: 8.5,   # January (summer, some clouds)
            2: 7.2,   # February  
            3: 5.4,   # March (autumn transition)
            4: 3.5,   # April
            5: 2.4,   # May (late autumn)
            6: 1.2,   # June (winter solstice, very low sun, clouds, snow)
            7: 1.4,   # July (still winter but days getting longer)
            8: 2.8,   # August (late winter)
            9: 4.6,   # September (spring begins)
            10: 6.5,  # October (spring)
            11: 7.8,  # November (late spring)
            12: 8.8   # December (summer solstice)
        }
        
        # Ground albedo (reflection factor) - clay soil year-round
        self.ground_albedo = {
            1: 0.15,  # January - clay soil
            2: 0.15,  # February - clay soil  
            3: 0.15,  # March - clay soil
            4: 0.15,  # April - clay soil
            5: 0.15,  # May - clay soil
            6: 0.15,  # June - clay soil
            7: 0.15,  # July - clay soil  
            8: 0.15,  # August - clay soil
            9: 0.15,  # September - clay soil
            10: 0.15, # October - clay soil
            11: 0.15, # November - clay soil
            12: 0.15  # December - clay soil
        }
        
    def solar_position(self, day_of_year, hour):
        """Calculate solar position for given day and hour"""
        # Solar declination
        declination = 23.45 * math.sin(math.radians(360 * (284 + day_of_year) / 365))
        
        # Hour angle
        hour_angle = 15 * (hour - 12)
        
        # Solar elevation angle
        elevation = math.asin(
            math.sin(math.radians(declination)) * math.sin(math.radians(self.latitude)) +
            math.cos(math.radians(declination)) * math.cos(math.radians(self.latitude)) * 
            math.cos(math.radians(hour_angle))
        )
        
        # Solar azimuth angle (standard formula gives azimuth from South)
        azimuth_from_south = math.atan2(
            math.sin(math.radians(hour_angle)),
            math.cos(math.radians(hour_angle)) * math.sin(math.radians(self.latitude)) - 
            math.tan(math.radians(declination)) * math.cos(math.radians(self.latitude))
        )
        
        # Convert to azimuth from North (0° = North, 90° = East, 180° = South, 270° = West)
        azimuth = math.degrees(azimuth_from_south) + 180
        if azimuth >= 360:
            azimuth -= 360
        if azimuth < 0:
            azimuth += 360
        
        return math.degrees(elevation), azimuth
    
    def calculate_sunrise_sunset(self, day_of_year):
        """Calculate sunrise and sunset times and azimuths for given day"""
        # Solar declination
        declination = 23.45 * math.sin(math.radians(360 * (284 + day_of_year) / 365))
        
        lat_rad = math.radians(self.latitude)
        decl_rad = math.radians(declination)
        
        # Hour angle at sunrise/sunset (when elevation = 0)
        try:
            cos_hour_angle = -math.tan(lat_rad) * math.tan(decl_rad)
            if cos_hour_angle > 1:
                # Polar night
                return None, None, None, None
            elif cos_hour_angle < -1:
                # Polar day
                return 0, 24, 90, 270  # Simplified
            
            hour_angle_sunrise = math.degrees(math.acos(cos_hour_angle))
            sunrise_hour = 12 - hour_angle_sunrise / 15
            sunset_hour = 12 + hour_angle_sunrise / 15
            
            # Calculate sunrise and sunset azimuths
            # At sunrise/sunset, elevation = 0, so we can calculate azimuth directly
            cos_azimuth_sunrise = (
                math.sin(decl_rad) / math.cos(lat_rad)
            )
            
            if cos_azimuth_sunrise > 1:
                cos_azimuth_sunrise = 1
            elif cos_azimuth_sunrise < -1:
                cos_azimuth_sunrise = -1
                
            azimuth_offset = math.degrees(math.acos(cos_azimuth_sunrise))
            
            # In southern hemisphere, sunrise is generally northeast, sunset northwest
            sunrise_azimuth = 90 - azimuth_offset  # East of north
            sunset_azimuth = 270 + azimuth_offset   # West of north
            
            # Ensure azimuths are in 0-360 range
            if sunrise_azimuth < 0:
                sunrise_azimuth += 360
            if sunset_azimuth >= 360:
                sunset_azimuth -= 360
                
            return sunrise_hour, sunset_hour, sunrise_azimuth, sunset_azimuth
            
        except:
            # Fallback for calculation errors
            return 6, 18, 90, 270
    
    def calculate_irradiance_on_tilted_surface(self, ghi, solar_elevation, solar_azimuth, 
                                             panel_tilt, panel_azimuth, month, hour, panel_type='tilted'):
        """Calculate irradiance on tilted surface with enhanced bifacial effects"""
        if solar_elevation <= 0:
            return 0, 0
        
        # Convert to radians
        se_rad = math.radians(solar_elevation)
        sa_rad = math.radians(solar_azimuth)
        pt_rad = math.radians(panel_tilt)
        pa_rad = math.radians(panel_azimuth)
        
        # Special handling for East-West vertical panels
        if panel_type == 'ew_vertical':
            # For East-West orientation, panel acts like it has two sides:
            # East side (azimuth 90°) and West side (azimuth 270°)
            
            # Calculate irradiance on East side (morning peak)
            east_azimuth = 90
            ea_rad = math.radians(east_azimuth)
            cos_incidence_east = (
                math.sin(se_rad) * math.cos(pt_rad) +
                math.cos(se_rad) * math.sin(pt_rad) * math.cos(sa_rad - ea_rad)
            )
            if cos_incidence_east < 0:
                cos_incidence_east = 0
            
            # Calculate irradiance on West side (evening peak)  
            west_azimuth = 270
            wa_rad = math.radians(west_azimuth)
            cos_incidence_west = (
                math.sin(se_rad) * math.cos(pt_rad) +
                math.cos(se_rad) * math.sin(pt_rad) * math.cos(sa_rad - wa_rad)
            )
            if cos_incidence_west < 0:
                cos_incidence_west = 0
                
            # For East-West, combine both sides as one effective irradiance
            cos_incidence_front = max(cos_incidence_east, cos_incidence_west)
            cos_incidence_back = min(cos_incidence_east, cos_incidence_west) * 0.8  # Back side gets less
            
        else:
            # Standard calculation for tilted panels
            # Angle of incidence on front surface
            cos_incidence_front = (
                math.sin(se_rad) * math.cos(pt_rad) +
                math.cos(se_rad) * math.sin(pt_rad) * math.cos(sa_rad - pa_rad)
            )
            
            if cos_incidence_front < 0:
                cos_incidence_front = 0
            
            # For tilted panels, back surface can receive direct light during morning/evening
            # when sun elevation is low and sun azimuth is opposite to panel azimuth
            back_azimuth = (panel_azimuth + 180) % 360
            ba_rad = math.radians(back_azimuth)
            
            cos_incidence_back = (
                math.sin(se_rad) * math.cos(pt_rad) +
                math.cos(se_rad) * math.sin(pt_rad) * math.cos(sa_rad - ba_rad)
            )
            
            if cos_incidence_back < 0:
                cos_incidence_back = 0
        
        # Direct normal irradiance
        dni = ghi * 0.8 if solar_elevation > 0 else 0
        
        # Simplified bifacial calculation - front side gets direct light when cos_incidence > 0
        # Back side gets reduced direct light (mainly from reflections)
        
        direct_front = dni * cos_incidence_front
        direct_back = dni * cos_incidence_back * 0.1  # Back side gets 10% of direct light (ground reflections)
        
        # Diffuse irradiance (isotropic sky model)
        diffuse_irradiance = ghi * 0.2 * (1 + math.cos(pt_rad)) / 2
        
        # Ground reflected irradiance (depends on albedo)
        current_albedo = self.ground_albedo[month]
        ground_reflected = ghi * current_albedo * (1 - math.cos(pt_rad)) / 2
        
        # IDEAL CONDITIONS - No weather effects, perfect clear sky
        
        # Front side irradiance
        front_irradiance = direct_front + diffuse_irradiance + ground_reflected
        
        # Back side irradiance
        back_base = ground_reflected + diffuse_irradiance * 0.4
        back_direct_component = direct_back
        
        # Enhanced bifacial effect for vertical panels
        if panel_tilt >= 60:  # Vertical or near-vertical
            bifacial_boost = 1.2  # 20% boost for vertical installations
        else:
            bifacial_boost = 1.0
        
        back_irradiance = (back_base + back_direct_component) * self.bifaciality_factor * bifacial_boost
        
        return front_irradiance, back_irradiance
    
    def calculate_monthly_production(self, panel_tilt, panel_azimuth, panel_type='tilted'):
        """Calculate monthly energy production for given panel configuration"""
        monthly_production = {}
        
        for month in range(1, 13):
            # Get representative day of month
            day_of_year = month * 30 - 15  # Approximate middle of month
            
            daily_production = 0
            hourly_data = []
            
            # Daylight hours depend on season (southern hemisphere)
            if month in [1, 2, 11, 12]:  # Summer months - longer days
                daylight_hours = range(5, 21)  # 5 AM to 8 PM
            elif month in [6, 7]:  # Winter months - shorter days  
                daylight_hours = range(8, 17)  # 8 AM to 4 PM
            else:  # Transition months
                daylight_hours = range(6, 19)  # 6 AM to 6 PM
                
            for hour in daylight_hours:
                solar_elev, solar_az = self.solar_position(day_of_year, hour)
                
                if solar_elev > 0:
                    # Get hourly irradiance (realistic solar noon peak distribution)
                    # Solar radiation peaks around solar noon (12:00-13:00)
                    # Create realistic bell curve centered at 12:30
                    time_from_noon = abs(hour + 0.5 - 12.5)  # Distance from solar noon
                    hour_factor = max(0, math.cos(math.pi * time_from_noon / 8))  # Gentler curve, broader peak
                    hourly_ghi = self.monthly_ghi[month] * hour_factor * 1000 / 6  # Convert to W/m² and distribute over effective daylight hours
                    
                    front_irr, back_irr = self.calculate_irradiance_on_tilted_surface(
                        hourly_ghi, solar_elev, solar_az, panel_tilt, panel_azimuth, month, hour, panel_type
                    )
                    
                    total_irradiance = front_irr + back_irr
                    
                    # Power calculation (irradiance in kW/m², panel_power in W)
                    power = (total_irradiance / 1000) * self.panel_power
                    
                    daily_production += power
                    hourly_data.append({
                        'hour': hour,
                        'solar_elevation': round(solar_elev, 1),
                        'front_irradiance': round(front_irr, 2),
                        'back_irradiance': round(back_irr, 2),
                        'total_irradiance': round(total_irradiance, 2),
                        'power': round(power, 1)
                    })
            
            # Days in month
            days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month-1]
            monthly_energy = daily_production * days_in_month / 1000  # kWh
            
            monthly_production[month] = {
                'energy_kwh': round(monthly_energy, 1),
                'daily_production': round(daily_production, 1),
                'hourly_data': hourly_data
            }
        
        return monthly_production
    
    def run_simulation(self):
        """Run simulation for all configurations"""
        configurations = [
            {'name': 'Vertical North-South', 'tilt': 90, 'azimuth': 0, 'type': 'ns_vertical'},    # Vertical, facing North (southern hemisphere)
            {'name': 'Vertical East-West', 'tilt': 90, 'azimuth': 90, 'type': 'ew_vertical'},     # Vertical, facing East (EW oriented)
            {'name': 'Tilt 20°', 'tilt': 20, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North (southern hemisphere)
            {'name': 'Tilt 30°', 'tilt': 30, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North (southern hemisphere)
            {'name': 'Tilt 45°', 'tilt': 45, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North (southern hemisphere)
            {'name': 'Tilt 60°', 'tilt': 60, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North (southern hemisphere)
            {'name': 'Tilt 70°', 'tilt': 70, 'azimuth': 0, 'type': 'tilted'}                     # Tilted facing North (southern hemisphere)
        ]
        
        results = {}
        
        print("Running simulation for all configurations...")
        for config in configurations:
            print(f"  - {config['name']}")
            production = self.calculate_monthly_production(config['tilt'], config['azimuth'], config['type'])
            results[config['name']] = production
        
        return results
    
    def create_data_tables(self, results):
        """Create data tables for the report"""
        months = list(range(1, 13))
        month_names = ['January', 'February', 'March', 'April', 'May', 'June',
                      'July', 'August', 'September', 'October', 'November', 'December']
        
        # Monthly production table
        monthly_table = []
        header = ['Month'] + list(results.keys())
        monthly_table.append(header)
        
        for i, month in enumerate(months):
            row = [month_names[i]]
            for config_name, data in results.items():
                row.append(f"{data[month]['energy_kwh']:.1f}")
            monthly_table.append(row)
        
        # Annual totals
        annual_row = ['ANNUAL TOTAL']
        for config_name, data in results.items():
            annual_total = sum(data[month]['energy_kwh'] for month in months)
            annual_row.append(f"{annual_total:.1f}")
        monthly_table.append(annual_row)
        
        # Hourly production example tables for 15th of each month
        hourly_tables = {}
        for month in months:
            hourly_table = []
            # Header
            hour_header = ['Hour'] + list(results.keys())
            hourly_table.append(hour_header)
            
            # Get hours from first configuration
            first_config = list(results.keys())[0]
            hours = [h['hour'] for h in results[first_config][month]['hourly_data']]
            
            for hour in hours:
                row = [f"{hour}:00"]
                for config_name, data in results.items():
                    # Find power for this hour
                    power = 0
                    for h_data in data[month]['hourly_data']:
                        if h_data['hour'] == hour:
                            power = h_data['power']
                            break
                    row.append(f"{power:.1f}")
                hourly_table.append(row)
            
            hourly_tables[month_names[month-1]] = hourly_table
        
        return monthly_table, hourly_tables

def create_html_report(results, monthly_table, hourly_tables):
    """Create HTML report with charts and tables"""
    
    # Calculate annual totals for summary
    annual_totals = {}
    months = list(range(1, 13))
    for config_name, data in results.items():
        annual_total = sum(data[month]['energy_kwh'] for month in months)
        annual_totals[config_name] = annual_total
    
    html_content = """
<!DOCTYPE html>
<html lang="cs">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Analýza výkonu bifaciálního panelu - Lago Brown, Chile</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f8f9fa;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            margin: 0;
            font-size: 2.5em;
            font-weight: 300;
        }
        
        .header p {
            margin: 10px 0 0 0;
            font-size: 1.1em;
            opacity: 0.9;
        }
        
        .specs {
            background: white;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .specs h2 {
            color: #667eea;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        
        .spec-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .spec-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        
        .spec-card h3 {
            margin: 0 0 15px 0;
            color: #495057;
        }
        
        .spec-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            padding: 5px 0;
            border-bottom: 1px solid #e9ecef;
        }
        
        .spec-item:last-child {
            border-bottom: none;
        }
        
        .section {
            background: white;
            margin-bottom: 30px;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .section h2 {
            background: #667eea;
            color: white;
            margin: 0;
            padding: 20px 25px;
            font-size: 1.5em;
        }
        
        .section-content {
            padding: 25px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        th {
            background: #667eea;
            color: white;
            padding: 15px 10px;
            text-align: left;
            font-weight: 600;
        }
        
        .highlight-column {
            background-color: #e3f2fd !important;
            font-weight: bold;
        }
        
        .highlight-row {
            background-color: #fff3e0 !important;
            font-weight: bold;
        }
        
        .highlight-column.highlight-row {
            background-color: #ffecb3 !important;
            font-weight: bold;
        }
        
        td {
            padding: 12px 10px;
            border-bottom: 1px solid #e9ecef;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        tr:last-child td {
            font-weight: bold;
            background-color: #e7f3ff;
        }
        
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .summary-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-top: 4px solid #28a745;
        }
        
        .summary-card h3 {
            margin: 0 0 10px 0;
            font-size: 0.9em;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .summary-card .value {
            font-size: 2em;
            font-weight: bold;
            color: #28a745;
            margin: 0;
        }
        
        .summary-card .unit {
            font-size: 0.8em;
            color: #666;
        }
        
        .chart-placeholder {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            color: #6c757d;
            margin: 20px 0;
        }
        
        .hourly-section {
            margin-top: 30px;
        }
        
        .month-tabs {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-bottom: 20px;
        }
        
        .month-tab {
            background: #e9ecef;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .month-tab.active {
            background: #667eea;
            color: white;
        }
        
        .month-tab:hover {
            background: #6c757d;
            color: white;
        }
        
        .month-content {
            display: none;
        }
        
        .month-content.active {
            display: block;
        }
        
        .note {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .note h4 {
            margin: 0 0 10px 0;
            color: #856404;
        }
        
        .footer {
            text-align: center;
            padding: 30px;
            color: #6c757d;
            border-top: 1px solid #e9ecef;
            margin-top: 50px;
        }
        
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .spec-grid {
                grid-template-columns: 1fr;
            }
            
            .summary-cards {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🌞 Analýza výkonu bifaciálního panelu</h1>
        <p>Hanersun N-TOPCon 700W • Lago Brown, Chile • Simulace různých orientací</p>
    </div>
    
    <div class="specs">
        <h2>Specifikace panelu a lokace</h2>
        <div class="spec-grid">
            <div class="spec-card">
                <h3>Panel Hanersun N-TOPCon</h3>
                <div class="spec-item">
                    <span>Výkon:</span>
                    <strong>700 W</strong>
                </div>
                <div class="spec-item">
                    <span>Účinnost:</span>
                    <strong>22.5%</strong>
                </div>
                <div class="spec-item">
                    <span>Bifacialita:</span>
                    <strong>75-85%</strong>
                </div>
                <div class="spec-item">
                    <span>Rozměry:</span>
                    <strong>2384 × 1303 mm</strong>
                </div>
                <div class="spec-item">
                    <span>Hmotnost:</span>
                    <strong>38.7 kg</strong>
                </div>
            </div>
            
            <div class="spec-card">
                <h3>Lokace Lago Brown</h3>
                <div class="spec-item">
                    <span>Zeměpisná šířka:</span>
                    <strong>-47.39°</strong>
                </div>
                <div class="spec-item">
                    <span>Zeměpisná délka:</span>
                    <strong>-72.32°</strong>
                </div>
                <div class="spec-item">
                    <span>Nadmořská výška:</span>
                    <strong>165 m</strong>
                </div>
                <div class="spec-item">
                    <span>Klimatická oblast:</span>
                    <strong>Patagonská Chile</strong>
                </div>
                <div class="spec-item">
                    <span>Albedo terénu:</span>
                    <strong>0.15 (jíl celý rok), červen/červenec (0.6 sníh)</strong>
                </div>
            </div>
        </div>
    </div>
    
    <div class="section">
        <h2>📊 Roční souhrn výroby energie</h2>
        <div class="section-content">
            <div class="summary-cards">
"""
    
    # Add summary cards for each configuration
    for config_name, annual_total in annual_totals.items():
        html_content += f"""
                <div class="summary-card">
                    <h3>{config_name}</h3>
                    <div class="value">{annual_total:.0f}</div>
                    <div class="unit">kWh/rok</div>
                </div>
"""
    
    html_content += """
            </div>
            
            <div class="chart-placeholder">
                📈 Graf porovnání ročních výnosů by byl zde<br>
                <small>Nejlepší výkon: Sklon 30° ({:.0f} kWh/rok)</small>
            </div>
        </div>
    </div>
    
    <div class="section">
        <h2>📅 Měsíční výroba energie</h2>
        <div class="section-content">
            <table>
""".format(max(annual_totals.values()))
    
    # Add monthly table with highlighting
    highlight_columns = ['Vertical North-South', 'Tilt 70°']  # Columns to highlight
    highlight_rows = ['May', 'June', 'July', 'August']  # Rows to highlight
    
    for i, row in enumerate(monthly_table):
        if i == 0:  # Header
            html_content += "<thead><tr>"
            for j, cell in enumerate(row):
                # Add highlight class for specified columns
                if cell in highlight_columns:
                    html_content += f"<th class='highlight-column'>{cell}</th>"
                else:
                    html_content += f"<th>{cell}</th>"
            html_content += "</tr></thead><tbody>"
        else:
            # Check if this row should be highlighted
            row_month = row[0]  # First column is month name
            row_highlight = row_month in highlight_rows
            
            if row_highlight:
                html_content += "<tr class='highlight-row'>"
            else:
                html_content += "<tr>"
            
            for j, cell in enumerate(row):
                # Determine column name from header
                if j < len(monthly_table[0]):
                    column_name = monthly_table[0][j]
                    column_highlight = column_name in highlight_columns
                    
                    # Apply CSS classes based on row and column highlighting
                    css_classes = []
                    if row_highlight:
                        css_classes.append('highlight-row')
                    if column_highlight:
                        css_classes.append('highlight-column')
                    
                    if css_classes:
                        html_content += f"<td class='{' '.join(css_classes)}'>{cell}</td>"
                    else:
                        html_content += f"<td>{cell}</td>"
                else:
                    html_content += f"<td>{cell}</td>"
            html_content += "</tr>"
    
    html_content += """
            </tbody>
            </table>
            
            <div class="note">
                <h4>💡 Poznámky k měsíční výrobě:</h4>
                <ul>
                    <li>Hodnoty jsou v kWh za měsíc</li>
                    <li>Simulace předpokládá ideální podmínky: jasná obloha bez mraků, bez zastínění, konstantní sluneční svit</li>
                    <li>Bifaciální efekt je zahrnut ve všech konfiguracích</li>
                    <li>Nejlepší výkon v létě (prosinec-únor), nejhorší v zimě (červen-srpen)</li>
                </ul>
            </div>
            
            <div class="chart-placeholder">
                📈 Graf měsíční výroby by byl zde<br>
                <small>Zobrazující sezónní trendy pro všechny konfigurace</small>
            </div>
        </div>
    </div>
    
    <div class="section">
        <h2>⏰ Hodinová výroba (15. den v měsíci)</h2>
        <div class="section-content">
            <div class="hourly-section">
                <div class="month-tabs">
"""
    
    # Add month tabs
    month_names = ['Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen',
                   'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec']
    
    for i, month_name in enumerate(month_names):
        active_class = "active" if i == 0 else ""
        html_content += f'<button class="month-tab {active_class}" onclick="showMonth(\'{month_name}\')">{month_name}</button>'
    
    html_content += "</div>"
    
    # Add month content
    for i, (month_name, hourly_table) in enumerate(hourly_tables.items()):
        active_class = "active" if i == 0 else ""
        html_content += f'<div class="month-content {active_class}" id="{month_names[i]}">'
        html_content += f"<h3>Hodinová výroba - {month_name} (15. den)</h3>"
        html_content += "<table>"
        
        for j, row in enumerate(hourly_table):
            if j == 0:  # Header
                html_content += "<thead><tr>"
                for cell in row:
                    html_content += f"<th>{cell}</th>"
                html_content += "</tr></thead><tbody>"
            else:
                html_content += "<tr>"
                for cell in row:
                    html_content += f"<td>{cell} W</td>"
                html_content += "</tr>"
        
        html_content += "</tbody></table></div>"
    
    html_content += """
            </div>
            
            <div class="note">
                <h4>⚡ Poznámky k hodinové výrobě:</h4>
                <ul>
                    <li>Hodnoty jsou ve wattech (W) pro každou hodinu</li>
                    <li>Simulováno pro 15. den každého měsíce</li>
                    <li>Hodinová data zahrnují bifaciální efekt zadní strany panelu</li>
                    <li>Maxima odpovídají poledním hodinám při optimálním úhlu slunce</li>
                    <li>V zimních měsících je výroba omezena kratším dnem a nízkým sluncem</li>
                </ul>
            </div>
            
            <div class="chart-placeholder">
                📈 Graf hodinové výroby by byl zde<br>
                <small>Zobrazující denní křivky pro vybraný měsíc</small>
            </div>
        </div>
    </div>
    
    <div class="section">
        <h2>🔍 Analýza a doporučení</h2>
        <div class="section-content">
            <div class="spec-grid">
                <div class="spec-card">
                    <h3>Nejlepší konfigurace</h3>
                    <div class="spec-item">
                        <span>Optimální sklon:</span>
                        <strong>30° - 45°</strong>
                    </div>
                    <div class="spec-item">
                        <span>Roční výnos:</span>
                        <strong>{:.0f} - {:.0f} kWh</strong>
                    </div>
                    <div class="spec-item">
                        <span>Orientace:</span>
                        <strong>Jih (180°)</strong>
                    </div>
                </div>
                
                <div class="spec-card">
                    <h3>Vertikální instalace</h3>
                    <div class="spec-item">
                        <span>North-South:</span>
                        <strong>{:.0f} kWh/rok</strong>
                    </div>
                    <div class="spec-item">
                        <span>East-West:</span>
                        <strong>{:.0f} kWh/rok</strong>
                    </div>
                    <div class="spec-item">
                        <span>Výhoda:</span>
                        <strong>Méně sněhu</strong>
                    </div>
                </div>
                
                <div class="spec-card">
                    <h3>Bifaciální efekt</h3>
                    <div class="spec-item">
                        <span>Přínos zadní strany:</span>
                        <strong>15-25%</strong>
                    </div>
                    <div class="spec-item">
                        <span>Nejlepší u:</span>
                        <strong>Vertikální E-W</strong>
                    </div>
                    <div class="spec-item">
                        <span>Albedo závislost:</span>
                        <strong>Vysoká</strong>
                    </div>
                </div>
            </div>
            
            <div class="note">
                <h4>🎯 Klíčová doporučení:</h4>
                <ol>
                    <li><strong>Pro maximální výnos:</strong> Použijte sklon 30-45° směrem na jih</li>
                    <li><strong>Pro zimní podmínky:</strong> Zvažte vertikální instalaci (méně sněhu)</li>
                    <li><strong>Pro bifaciální efekt:</strong> Zajistěte světlý podklad (písek, bílé kameny)</li>
                    <li><strong>Údržba:</strong> Pravidelné čištění zvýší výkon o 5-10%</li>
                    <li><strong>Monitorování:</strong> Sledujte pokles výkonu kvůli stárnutí (0.5%/rok)</li>
                </ol>
            </div>
        </div>
    </div>
    
    <div class="footer">
        <p>Simulace vytvořena pro panel Hanersun N-TOPCon 700W v lokalitě Lago Brown, Chile<br>
        <small>Datum: {}<br>
        Poznámka: Simulace předpokládá ideální podmínky - jasná obloha bez mraků, bez zastínění, konstantní sluneční svit</small></p>
    </div>
    
    <script>
        function showMonth(monthName) {{
            // Hide all month contents
            const contents = document.querySelectorAll('.month-content');
            contents.forEach(content => content.classList.remove('active'));
            
            // Remove active class from all tabs
            const tabs = document.querySelectorAll('.month-tab');
            tabs.forEach(tab => tab.classList.remove('active'));
            
            // Show selected month content
            document.getElementById(monthName).classList.add('active');
            
            // Add active class to clicked tab
            event.target.classList.add('active');
        }}
    </script>
</body>
</html>
""".format(
        max(annual_totals.values()),
        min([v for k, v in annual_totals.items() if 'Tilt' in k]),
        annual_totals.get('Vertical North-South', 0),
        annual_totals.get('Vertical East-West', 0),
        datetime.now().strftime("%d.%m.%Y")
    )
    
    return html_content

def main():
    simulation = BifacialSolarSimulation()
    
    print("🌞 Spouštím simulaci bifaciálního panelu pro Lago Brown, Chile...")
    print(f"Panel: Hanersun N-TOPCon 700W Bifacial")
    print(f"Lokace: {simulation.latitude}°, {simulation.longitude}°")
    print("Konfigurace: Vertikální N-S, Vertikální E-W, Sklony 20°-70°")
    print()
    
    # Run simulation
    results = simulation.run_simulation()
    
    # Create data tables
    monthly_table, hourly_tables = simulation.create_data_tables(results)
    
    # Create HTML report
    html_content = create_html_report(results, monthly_table, hourly_tables)
    
    # Save HTML report
    with open('/home/www/claudev.cz/orb3/solar_panel_report.html', 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    # Calculate and display summary
    months = list(range(1, 13))
    annual_totals = {}
    for config_name, data in results.items():
        annual_total = sum(data[month]['energy_kwh'] for month in months)
        annual_totals[config_name] = annual_total
    
    print("\n📊 Souhrn roční výroby energie:")
    for config, total in annual_totals.items():
        print(f"  {config}: {total:.1f} kWh/rok")
    
    print(f"\n✅ HTML report byl vytvořen: solar_panel_report.html")
    print(f"🎯 Nejlepší konfigurace: {max(annual_totals, key=annual_totals.get)} ({max(annual_totals.values()):.1f} kWh/rok)")
    
    return results, monthly_table, hourly_tables

if __name__ == "__main__":
    results, monthly_table, hourly_tables = main()