#!/usr/bin/env python3
"""
Verify that the plugin uses REAL data from the scraper
"""

import json
import subprocess
import sys
import os

def test_real_data():
    print("=== Verifying REAL Data Flow ===")
    
    # Test 1: Run the scraper directly
    print("1. Testing Python scraper...")
    try:
        result = subprocess.run(['python3', 'solar_scraper.py'], 
                              capture_output=True, text=True, timeout=60)
        
        if result.returncode == 0:
            # Find the JSON output
            lines = result.stdout.split('\n')
            json_data = None
            for line in reversed(lines):
                if line.strip().startswith('{'):
                    try:
                        json_data = json.loads(line)
                        break
                    except json.JSONDecodeError:
                        continue
            
            if json_data:
                print("✅ Scraper returned REAL data:")
                print(f"   Current Power: {json_data.get('current_power', 'N/A')}")
                print(f"   Today Energy: {json_data.get('today_energy', 'N/A')}")
                print(f"   Yesterday Energy: {json_data.get('yesterday_energy', 'N/A')}")
                print(f"   Monthly Energy: {json_data.get('monthly_energy', 'N/A')}")
                
                # Verify data looks real (not dummy)
                current_power = json_data.get('current_power', '')
                if 'kW' in current_power and not current_power.startswith('0 kW'):
                    print("✅ Data appears to be REAL (not dummy)")
                else:
                    print("⚠️  Data might be dummy - check scraper")
                
                return json_data
            else:
                print("❌ No JSON data found in scraper output")
                return None
        else:
            print(f"❌ Scraper failed: {result.stderr}")
            return None
            
    except subprocess.TimeoutExpired:
        print("❌ Scraper timed out")
        return None
    except Exception as e:
        print(f"❌ Scraper error: {e}")
        return None

def test_plugin_integration():
    print("\n2. Testing plugin integration...")
    
    # Simulate what the plugin does
    try:
        # Run scraper and capture output
        result = subprocess.run(['python3', 'solar_scraper.py'], 
                              capture_output=True, text=True, timeout=60)
        
        if result.returncode == 0:
            # Parse the last JSON line (like the plugin does)
            lines = result.stdout.split('\n')
            for i in range(len(lines) - 1, -1, -1):
                if lines[i].strip().startswith('{'):
                    try:
                        data = json.loads(lines[i])
                        print("✅ Plugin would receive this REAL data:")
                        print(json.dumps(data, indent=2))
                        return data
                    except json.JSONDecodeError:
                        continue
            
            print("❌ Plugin would not receive valid JSON")
            return None
        else:
            print("❌ Plugin would fail to get data")
            return None
            
    except Exception as e:
        print(f"❌ Plugin integration test failed: {e}")
        return None

def main():
    print("🔍 Verifying REAL data flow for Homebridge plugin...\n")
    
    # Test 1: Direct scraper
    real_data = test_real_data()
    
    # Test 2: Plugin integration
    plugin_data = test_plugin_integration()
    
    print("\n=== Summary ===")
    if real_data and plugin_data:
        print("✅ REAL data flow confirmed!")
        print("✅ Plugin will receive REAL data from e-SenZ")
        print("✅ No dummy/test data will be sent")
        print("\n📊 Expected plugin behavior:")
        print("   - Every 15 minutes: Scrape e-SenZ → Get REAL data → Update HomeKit + Pushover")
        print("   - Time-based: Only during 6 AM - 6:30 PM IST")
        print("   - Data source: Always fresh from e-SenZ website")
    else:
        print("❌ REAL data flow issues detected")
        print("   - Check Python dependencies: pip3 install -r requirements.txt")
        print("   - Check e-SenZ credentials in solar_scraper.py")
        print("   - Check internet connection")

if __name__ == "__main__":
    main() 