#!/usr/bin/env python3
"""Dump all raw protobuf fields using the same logic as _get_status_once"""

import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from duosida_ev.charger import DuosidaCharger, ProtobufDecoder

def main():
    charger = DuosidaCharger(
        host="192.168.20.95",
        device_id="0310107112122360374",
        debug=True
    )

    if not charger.connect():
        print("Failed to connect")
        return

    print("Connected. Reading raw status...\n")

    try:
        import time

        # Read multiple responses to find DataVendorStatusReq
        for attempt in range(10):
            time.sleep(0.5)
            try:
                response = charger._recv_raw(timeout=2.0)
            except:
                continue

            if not response:
                continue

            outer_fields = ProtobufDecoder.decode_message(response)

            if 16 not in outer_fields:
                continue

            inner_data = outer_fields[16]
            if not isinstance(inner_data, bytes):
                continue

            inner_fields = ProtobufDecoder.decode_message(inner_data)
            msg_type = inner_fields.get(2, "")

            if msg_type != "DataVendorStatusReq":
                print(f"Attempt {attempt+1}: Got {msg_type}, waiting...")
                continue

            print(f"Attempt {attempt+1}: Found DataVendorStatusReq!\n")

            # Parse status data from field 10
            if 10 in inner_fields and isinstance(inner_fields[10], bytes):
                status_data = inner_fields[10]
                fields = ProtobufDecoder.decode_message(status_data)

                print("=== RAW STATUS FIELDS ===")
                for field_num in sorted(fields.keys()):
                    value = fields[field_num]
                    if isinstance(value, float):
                        print(f"  Field {field_num:2d}: {value:12.2f}")
                    elif isinstance(value, bytes):
                        try:
                            decoded = value.decode('utf-8')
                            print(f"  Field {field_num:2d}: {decoded} (string)")
                        except:
                            print(f"  Field {field_num:2d}: <bytes> len={len(value)}")
                    else:
                        print(f"  Field {field_num:2d}: {value}")

                # Highlight potential CP voltage fields
                print("\n=== POTENTIAL CP VOLTAGE FIELDS ===")
                for field_num in [9, 15, 16]:
                    if field_num in fields:
                        value = fields[field_num]
                        if isinstance(value, (int, float)):
                            print(f"  Field {field_num}: {float(value):.2f} V")

                break
        else:
            print("Failed to get DataVendorStatusReq after 5 attempts")

    finally:
        charger.disconnect()
        print("\nDisconnected")

if __name__ == "__main__":
    main()
