import math
import json
from datetime import datetime, timedelta
from astral import LocationInfo
from astral.sun import sun, elevation, azimuth
import pytz

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.location = LocationInfo("Lago Brown", "Chile", "America/Santiago", -47.3919449, -72.3174973)
        self.timezone = pytz.timezone('America/Santiago')
        
        # Direct Normal Irradiance - constant when sun is shining (ideal conditions)
        self.dni_clear_sky = 900  # W/m² for clear sky conditions
        
        # Ground albedo (reflection factor) - clay soil year-round
        self.ground_albedo = 0.15
        
    def get_solar_position(self, date, hour, minute=0):
        """Get precise solar position using astronomical calculations"""
        dt = datetime(date.year, date.month, date.day, hour, minute, 0)
        dt = self.timezone.localize(dt)
        
        # Get solar elevation and azimuth
        solar_elevation = elevation(self.location.observer, dt)
        solar_azimuth = azimuth(self.location.observer, dt)
        
        return solar_elevation, solar_azimuth
    
    def calculate_angle_of_incidence(self, solar_elevation, solar_azimuth, panel_tilt, panel_azimuth):
        """Calculate angle of incidence between sun and panel surface"""
        if solar_elevation <= 0:
            return 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)
        
        # Standard angle of incidence formula
        cos_incidence = (
            math.sin(se_rad) * math.cos(pt_rad) +
            math.cos(se_rad) * math.sin(pt_rad) * math.cos(sa_rad - pa_rad)
        )
        
        return cos_incidence
    
    def calculate_bifacial_irradiance(self, solar_elevation, solar_azimuth, panel_tilt, panel_azimuth):
        """Calculate irradiance with proper bifacial physics"""
        if solar_elevation <= 0:
            return 0, 0
            
        # Standard angle of incidence for front side
        front_cos = self.calculate_angle_of_incidence(solar_elevation, solar_azimuth, panel_tilt, panel_azimuth)
        
        # Back side angle of incidence  
        back_azimuth = (panel_azimuth + 180) % 360
        back_cos = self.calculate_angle_of_incidence(solar_elevation, solar_azimuth, panel_tilt, back_azimuth)
        
        # Determine illumination scenario
        azimuth_to_front = abs(solar_azimuth - panel_azimuth)
        if azimuth_to_front > 180:
            azimuth_to_front = 360 - azimuth_to_front
        
        azimuth_to_back = abs(solar_azimuth - back_azimuth)  
        if azimuth_to_back > 180:
            azimuth_to_back = 360 - azimuth_to_back
            
        # Determine primary illumination direction
        if azimuth_to_front < 90:  # Front illumination (±90° from front)
            front_irr = self.dni_clear_sky * max(0, front_cos)
            back_irr = 0
        elif azimuth_to_back < 90:  # Back illumination - SPECIAL BIFACIAL PHYSICS
            front_irr = 0
            if back_cos > 0:
                # For back illumination, vertical panels have significant advantage at low sun
                if solar_elevation < 30:  # Low sun - bifacial geometry critical
                    if panel_tilt == 90:  # Vertical panel - best bifacial geometry
                        bifacial_geometry_factor = 1.2  # 20% bonus for optimal geometry
                    else:
                        # Tilted panels lose efficiency for low sun back-illumination
                        # More tilted = further from vertical = worse bifacial geometry
                        vertical_deviation = abs(90 - panel_tilt) / 90.0
                        bifacial_geometry_factor = 1.0 - 0.4 * vertical_deviation  # Stronger penalty
                else:
                    bifacial_geometry_factor = 1.0  # High sun - less geometry effect
                    
                back_irr = self.dni_clear_sky * back_cos * self.bifaciality_factor * bifacial_geometry_factor
            else:
                back_irr = 0
        else:
            # Side illumination - minimal direct light
            front_irr = self.dni_clear_sky * max(0, front_cos) * 0.5  # Reduced efficiency
            back_irr = self.dni_clear_sky * max(0, back_cos) * self.bifaciality_factor * 0.5
            
        return front_irr, back_irr
    
    def calculate_panel_irradiance(self, date, hour, minute, panel_tilt, panel_azimuth, panel_type='tilted'):
        """Calculate irradiance using simplified but physically accurate approach"""
        solar_elev, solar_az = self.get_solar_position(date, hour, minute)
        
        if solar_elev <= 0:
            return 0, 0  # No sun
        
        if panel_type == 'ew_vertical':
            # East-West vertical panel
            east_cos = self.calculate_angle_of_incidence(solar_elev, solar_az, panel_tilt, 90)
            west_cos = self.calculate_angle_of_incidence(solar_elev, solar_az, panel_tilt, 270)
            
            if east_cos > west_cos and east_cos > 0:
                front_direct = self.dni_clear_sky * east_cos
                back_direct = self.dni_clear_sky * west_cos * self.bifaciality_factor if west_cos > 0 else 0
            else:
                front_direct = self.dni_clear_sky * west_cos if west_cos > 0 else 0
                back_direct = self.dni_clear_sky * east_cos * self.bifaciality_factor if east_cos > 0 else 0
        else:
            # North-South panel with proper bifacial physics
            front_direct, back_direct = self.calculate_bifacial_irradiance(
                solar_elev, solar_az, panel_tilt, panel_azimuth)
        
        # Diffuse irradiance (sky radiation)
        diffuse_factor = 0.15
        sky_diffuse = self.dni_clear_sky * diffuse_factor
        
        front_diffuse = sky_diffuse * (1 + math.cos(math.radians(panel_tilt))) / 2
        back_diffuse = sky_diffuse * (1 - math.cos(math.radians(panel_tilt))) / 2
        
        # Ground reflected irradiance
        ground_reflected = self.dni_clear_sky * math.sin(math.radians(solar_elev)) * self.ground_albedo
        front_ground = ground_reflected * (1 - math.cos(math.radians(panel_tilt))) / 2
        back_ground = ground_reflected * (1 + math.cos(math.radians(panel_tilt))) / 2
        
        # Apply bifacial efficiency to back side indirect components
        angle_from_vertical = abs(90 - panel_tilt)
        bifacial_efficiency = 1.0 - (angle_from_vertical / 90.0)
        back_indirect_factor = self.bifaciality_factor * (0.4 + 0.6 * bifacial_efficiency)
        
        # Total irradiance
        front_irradiance = front_direct + front_diffuse + front_ground
        back_irradiance = back_direct + (back_diffuse + back_ground) * back_indirect_factor
        
        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):
            # Representative date for month (15th day)
            date = datetime(2024, month, 15)
            
            daily_production = 0
            half_hourly_data = []
            
            # Calculate for each half hour of the day (48 intervals)
            for half_hour in range(48):
                hour = half_hour // 2
                minute = 0 if half_hour % 2 == 0 else 30
                
                front_irr, back_irr = self.calculate_panel_irradiance(date, hour, minute, panel_tilt, panel_azimuth, panel_type)
                
                if front_irr > 0 or back_irr > 0:
                    total_irradiance = front_irr + back_irr
                    
                    # Power calculation: Irradiance (W/m²) × Panel area × Panel efficiency
                    power = (total_irradiance / 1000) * self.panel_power
                    
                    # Energy for 30 minutes (0.5 hour)
                    daily_production += power * 0.5
                    
                    # Calculate bifacial contribution percentage
                    bifacial_contribution = (back_irr / total_irradiance * 100) if total_irradiance > 0 else 0
                    
                    time_str = f"{hour:02d}:{minute:02d}"
                    half_hourly_data.append({
                        'time': time_str,
                        'solar_elevation': round(self.get_solar_position(date, hour, minute)[0], 1),
                        'front_irradiance': round(front_irr, 2),
                        'back_irradiance': round(back_irr, 2),
                        'total_irradiance': round(total_irradiance, 2),
                        'power': round(power, 1),
                        'bifacial_contribution': round(bifacial_contribution, 1)
                    })
                else:
                    time_str = f"{hour:02d}:{minute:02d}"
                    half_hourly_data.append({
                        'time': time_str,
                        'solar_elevation': 0,
                        'front_irradiance': 0,
                        'back_irradiance': 0,
                        'total_irradiance': 0,
                        'power': 0,
                        'bifacial_contribution': 0
                    })
            
            # 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),
                'half_hourly_data': half_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
            {'name': 'Vertical East-West', 'tilt': 90, 'azimuth': 90, 'type': 'ew_vertical'},     # Vertical, E-W oriented
            {'name': 'Tilt 20°', 'tilt': 20, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North
            {'name': 'Tilt 30°', 'tilt': 30, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North
            {'name': 'Tilt 45°', 'tilt': 45, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North
            {'name': 'Tilt 60°', 'tilt': 60, 'azimuth': 0, 'type': 'tilted'},                    # Tilted facing North
            {'name': 'Tilt 70°', 'tilt': 70, 'azimuth': 0, 'type': 'tilted'}                     # Tilted facing North
        ]
        
        results = {}
        
        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 generate_html_report(self, results):
        """Generate comprehensive HTML report"""
        # Calculate annual totals
        annual_totals = {}
        for config_name, data in results.items():
            annual_total = sum(data[month]['energy_kwh'] for month in range(1, 13))
            annual_totals[config_name] = annual_total
        
        # Find best configuration
        best_config = max(annual_totals, key=annual_totals.get)
        best_value = annual_totals[best_config]
        
        months_czech = ['Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen',
                       'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec']
        months_english = ['January', 'February', 'March', 'April', 'May', 'June',
                         'July', 'August', 'September', 'October', 'November', 'December']
        
        html_content = f"""<!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;
        }}
        
        .legend {{
            background: #e8f4fd;
            border: 1px solid #bee5eb;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }}
        
        .legend h4 {{
            margin: 0 0 10px 0;
            color: #0c5460;
        }}
        
        .legend-item {{
            display: inline-block;
            margin-right: 20px;
            margin-bottom: 5px;
        }}
        
        .elevation-info {{
            color: #dc3545;
            font-weight: bold;
        }}
        
        .azimuth-info {{
            color: #fd7e14;
            font-weight: bold;
        }}
        
        .bifacial-info {{
            color: #198754;
            font-weight: bold;
        }}
        
        .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 • Astronomická simulace</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)</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 config_name in ['Vertical North-South', 'Vertical East-West', 'Tilt 20°', 'Tilt 30°', 'Tilt 45°', 'Tilt 60°', 'Tilt 70°']:
            annual_value = int(annual_totals[config_name])
            html_content += f"""
                <div class="summary-card">
                    <h3>{config_name}</h3>
                    <div class="value">{annual_value}</div>
                    <div class="unit">kWh/rok</div>
                </div>
"""
        
        html_content += f"""
            </div>
            
            <div class="chart-placeholder">
                📈 Graf porovnání ročních výnosů by byl zde<br>
                <small>Nejlepší výkon: {best_config} ({int(best_value)} kWh/rok)</small>
            </div>
        </div>
    </div>
    
    <div class="section">
        <h2>📅 Měsíční výroba energie</h2>
        <div class="section-content">
            <table>
<thead><tr><th>Month</th><th class='highlight-column'>Vertical North-South</th><th>Vertical East-West</th><th>Tilt 20°</th><th>Tilt 30°</th><th>Tilt 45°</th><th>Tilt 60°</th><th class='highlight-column'>Tilt 70°</th></tr></thead><tbody>"""
        
        # Monthly data table
        config_order = ['Vertical North-South', 'Vertical East-West', 'Tilt 20°', 'Tilt 30°', 'Tilt 45°', 'Tilt 60°', 'Tilt 70°']
        
        for month in range(1, 13):
            month_name = months_english[month-1]
            row_class = 'highlight-row' if month in [5, 6, 7, 8] else ''
            html_content += f"<tr class='{row_class}'><td class='{row_class}'>{month_name}</td>"
            
            for config in config_order:
                value = results[config][month]['energy_kwh']
                col_class = 'highlight-column' if config in ['Vertical North-South', 'Tilt 70°'] else ''
                if row_class and col_class:
                    col_class += ' highlight-row'
                elif row_class:
                    col_class = 'highlight-row'
                html_content += f"<td class='{col_class}'>{value}</td>"
            html_content += "</tr>"
        
        # Annual total row
        html_content += "<tr><td>ANNUAL TOTAL</td>"
        for config in config_order:
            annual_value = annual_totals[config]
            col_class = 'highlight-column' if config in ['Vertical North-South', 'Tilt 70°'] else ''
            html_content += f"<td class='{col_class}'>{annual_value:.1f}</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 používá přesné astronomické výpočty pro pozici slunce</li>
                    <li>Počítá s ideálními podmínkami: jasná obloha, bez mraků, bez zastínění</li>
                    <li>Bifaciální efekt je zahrnut ve všech konfiguracích</li>
                    <li>Panely směřují na sever (jižní polokoule)</li>
                </ul>
            </div>
        </div>
    </div>
    
    <div class="section">
        <h2>⏰ Půlhodinová výroba (15. den v měsíci)</h2>
        <div class="section-content">
            <div class="half-hourly-section">
                <div class="month-tabs">"""
        
        # Month tabs
        for i, month_name in enumerate(months_czech):
            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>"
        
        # Half-hourly data for each month
        for month in range(1, 13):
            month_name = months_czech[month-1]
            month_name_en = months_english[month-1]
            active_class = 'active' if month == 1 else ''
            
            html_content += f"""<div class="month-content {active_class}" id="{month_name}"><h3>Půlhodinová výroba - {month_name_en} (15. den)</h3><table><thead><tr><th>Time (Elevation/Azimuth)</th><th>Vertical North-South</th><th>Vertical East-West</th><th>Tilt 20°</th><th>Tilt 30°</th><th>Tilt 45°</th><th>Tilt 60°</th><th>Tilt 70°</th></tr></thead><tbody>"""
            
            # Find times with production
            half_hourly_data = {}
            for config in config_order:
                half_hourly_data[config] = results[config][month]['half_hourly_data']
            
            # Get all daylight times (when sun is above horizon)
            all_times = []
            date = datetime(2024, month, 15)
            for half_hour in range(48):
                hour = half_hour // 2
                minute = 0 if half_hour % 2 == 0 else 30
                solar_elev, solar_az = self.get_solar_position(date, hour, minute)
                if solar_elev > 0:  # Sun is above horizon
                    time_str = f"{hour:02d}:{minute:02d}"
                    all_times.append((time_str, solar_elev, solar_az))
            
            if all_times:
                for time_str, solar_elev, solar_az in all_times:
                    html_content += f"<tr><td>{time_str}<br>(<span class='elevation-info'>{solar_elev:.1f}°</span>/<span class='azimuth-info'>{solar_az:.0f}°</span>)</td>"
                    for config in config_order:
                        power = 0
                        bifacial_contrib = 0
                        for time_data in half_hourly_data[config]:
                            if time_data['time'] == time_str:
                                power = time_data['power']
                                bifacial_contrib = time_data['bifacial_contribution']
                                break
                        if bifacial_contrib > 0:
                            html_content += f"<td>{power:.1f} W<br>(<span class='bifacial-info'>{bifacial_contrib:.1f}%</span>)</td>"
                        else:
                            html_content += f"<td>{power:.1f} W</td>"
                    html_content += "</tr>"
            else:
                html_content += "<tr><td colspan='8'>Žádná výroba v tomto měsíci</td></tr>"
            
            html_content += "</tbody></table></div>"
        
        html_content += """
            </div>
            
            <div class="legend">
                <h4>🎨 Legenda barevného označení:</h4>
                <div class="legend-item">
                    <span class="elevation-info">9.7°</span> - Elevace slunce (výška nad horizontem)
                </div>
                <div class="legend-item">
                    <span class="azimuth-info">39°</span> - Azimut slunce (směr od severu)
                </div>
                <div class="legend-item">
                    <span class="bifacial-info">7.6%</span> - Bifaciální příspěvek (% ze zadní strany panelu)
                </div>
            </div>
            
            <div class="note">
                <h4>⚡ Poznámky k půlhodinové výrobě:</h4>
                <ul>
                    <li>Hodnoty jsou ve wattech (W) pro každých 30 minut</li>
                    <li>Simulováno pro 15. den každého měsíce</li>
                    <li>Používá přesné astronomické výpočty pozice slunce</li>
                    <li>Půlhodinová data zahrnují bifaciální efekt zadní strany panelu</li>
                    <li>Zobrazeny pouze časy s výrobou energie</li>
                    <li><strong>Elevace:</strong> čím vyšší, tím silnější slunce</li>
                    <li><strong>Azimut:</strong> 0°=sever, 90°=východ, 180°=jih, 270°=západ</li>
                    <li><strong>Bifaciální %:</strong> podíl energie ze zadní strany panelu</li>
                </ul>
            </div>
        </div>
    </div>
    
    <div class="footer">
        <p>Astronomická simulace vytvořena pro panel Hanersun N-TOPCon 700W v lokalitě Lago Brown, Chile<br>
        <small>Datum: 12.08.2025<br>
        Poznámka: Simulace používá přesné astronomické výpočty a předpokládá ideální podmínky - jasná obloha bez mraků</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>"""
        
        with open('/home/www/claudev.cz/orb3/solar_panel_report.html', 'w', encoding='utf-8') as f:
            f.write(html_content)

def main():
    simulation = BifacialSolarSimulation()
    
    print("🌞 Spouštím astronomickou simulaci bifaciálního panelu pro Lago Brown, Chile...")
    print(f"Panel: Hanersun N-TOPCon 700W Bifacial")
    print(f"Lokace: {simulation.location.latitude}°, {simulation.location.longitude}°")
    print("Konfigurace: Vertikální N-S, Vertikální E-W, Sklony 20°-70°")
    print()
    
    # Run simulation
    print("Running astronomical simulation for all configurations...")
    results = simulation.run_simulation()
    
    # Calculate annual totals
    annual_totals = {}
    for config_name, data in results.items():
        annual_total = sum(data[month]['energy_kwh'] for month in range(1, 13))
        annual_totals[config_name] = annual_total
    
    print()
    print("📊 Souhrn roční výroby energie:")
    for config, total in annual_totals.items():
        print(f"  {config}: {total:.1f} kWh/rok")
    
    # Generate HTML report
    simulation.generate_html_report(results)
    print()
    print("✅ HTML report byl vytvořen: solar_panel_report.html")
    
    # Find best configuration
    best_config = max(annual_totals, key=annual_totals.get)
    best_value = annual_totals[best_config]
    print(f"🎯 Nejlepší konfigurace: {best_config} ({best_value:.1f} kWh/rok)")
    
    return results, annual_totals

if __name__ == "__main__":
    results, annual_totals = main()