import asyncio
import os
import matplotlib.pyplot as plt
import sys
from dotenv import load_dotenv
from huawei_solar_tools.devices.meter import Meter
import huawei_solar_tools.registers.meter_register_names as mrn

async def main():
    # Load environment variables
    load_dotenv("huawei_conf.env")
    host = os.getenv("SMARTLOGGER_IP")
    port = int(os.getenv("SMARTLOGGER_PORT"))
    meter_ids = [int(i) for i in os.getenv("METER_IDS").split(",")]  

    for device_id in meter_ids:
        # Set up individual report file for each Meter
        script_dir = os.path.dirname(os.path.abspath(__file__))
        reports_dir = os.path.join(script_dir, "meter_reports")
        os.makedirs(reports_dir, exist_ok=True)
        report_file = os.path.join(reports_dir, f"meter_{device_id}_report.txt")

        with open(report_file, "w") as report:
            sys.stdout = report

            print(f"Connecting to meter {device_id}...")

            # Initialize the Inverter
            meter = Meter(host, port, device_id)

            try:
                # Test connection
                await meter.connect()
                print("Connection successful.")

                # Test connection status
                print(f"Is Meter {device_id} connected? {meter.is_connected()}")

                # Test getting device ID
                print(f"Meter ID: {meter.get_device_id()}")

                # Test reading all registers
                results = await meter.read_all_registers()
                print("All Registers:")
                for i in results:
                    print(i)

                # Test reading a specific register (grid frequency)
                freq = await meter.read_raw_register(37118, 1)
                print(f"Grid Frequency: {freq[0] / 100} Hz")

                # Test reading a specific register by name (Serial Number)
                meter_status = await meter.read_register_by_name(mrn.METER_STATUS)
                print(f"Meter Status: {meter_status}")
                
            except Exception as e:
                print(f"Error processing Meter {device_id}: {e}")

            finally:
                # Test disconnection
                meter.disconnect()
                print(f"Disconnected from Meter {device_id}.")

if __name__ == "__main__":
    asyncio.run(main())
