#!/usr/bin/env python3
"""Debug all message types including DataContinueReq"""

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 all messages...\n")

    try:
        import time

        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, "")

            print(f"=== Message {attempt+1}: {msg_type} ===")

            # Parse based on message type
            if msg_type == "DataVendorStatusReq":
                if 10 in inner_fields and isinstance(inner_fields[10], bytes):
                    status_data = inner_fields[10]
                    fields = ProtobufDecoder.decode_message(status_data)
                    print("Field 10 (status data):")
                    for field_num in sorted(fields.keys()):
                        value = fields[field_num]
                        if isinstance(value, float):
                            print(f"  Field {field_num:2d}: {value:15.2f}")
                        elif isinstance(value, bytes):
                            try:
                                decoded = value.decode('utf-8')
                                print(f"  Field {field_num:2d}: {decoded}")
                            except:
                                print(f"  Field {field_num:2d}: <bytes> len={len(value)}")
                        else:
                            print(f"  Field {field_num:2d}: {value}")

            elif msg_type == "DataContinueReq":
                # Check field 12 for DataContinueReq data
                if 12 in inner_fields and isinstance(inner_fields[12], bytes):
                    continue_data = inner_fields[12]
                    fields = ProtobufDecoder.decode_message(continue_data)
                    print("Field 12 (continue data):")
                    for field_num in sorted(fields.keys()):
                        value = fields[field_num]
                        if isinstance(value, float):
                            print(f"  Field {field_num:2d}: {value:15.2f}")
                        elif isinstance(value, bytes):
                            try:
                                decoded = value.decode('utf-8')
                                print(f"  Field {field_num:2d}: {decoded}")
                            except:
                                # Try to decode nested message
                                nested = ProtobufDecoder.decode_message(value)
                                if nested:
                                    print(f"  Field {field_num:2d}: <nested message>")
                                    for nf, nv in sorted(nested.items()):
                                        if isinstance(nv, float):
                                            print(f"    Field {nf}: {nv:.2f}")
                                        else:
                                            print(f"    Field {nf}: {nv}")
                                else:
                                    print(f"  Field {field_num:2d}: <bytes> len={len(value)}")
                        else:
                            print(f"  Field {field_num:2d}: {value}")

            print()

    finally:
        charger.disconnect()
        print("Disconnected")

if __name__ == "__main__":
    main()
