#!/usr/bin/env python3
"""Debug script to dump all raw protobuf fields from charger response"""

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

from duosida_ev.charger import DuosidaCharger, ProtobufDecoder
from duosida_ev.discovery import discover_chargers

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--host', help='Charger IP address')
    parser.add_argument('--device-id', help='Device ID')
    args = parser.parse_args()

    if args.host and args.device_id:
        device = {'ip': args.host, 'device_id': args.device_id}
        print(f"Using: {device['ip']} - {device['device_id']}")
    else:
        # Discover charger
        print("Discovering chargers (timeout 10s)...")
        devices = discover_chargers(timeout=10)

        if not devices:
            print("No chargers found. Use --host and --device-id to specify manually.")
            return

        device = devices[0]
        print(f"Found: {device['ip']} - {device['device_id']}")

    # Connect
    charger = DuosidaCharger(
        host=device['ip'],
        device_id=device['device_id'],
        debug=True
    )

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

    print("\nConnected. Reading raw response...\n")

    # Get raw response - read multiple times to find DataVendorStatusReq
    try:
        import time

        for attempt in range(5):
            time.sleep(1)
            response = charger._recv_raw(timeout=3.0)

            if not response:
                print(f"Attempt {attempt+1}: No response received")
                continue

            # Quick check for message type
            if b'DataVendorStatusReq' in response:
                print(f"Attempt {attempt+1}: Found DataVendorStatusReq!")
                break
            elif b'DataContinueReq' in response:
                print(f"Attempt {attempt+1}: Got DataContinueReq, waiting for status...")
                continue
            else:
                print(f"Attempt {attempt+1}: Got unknown message type")

        if not response:
            print("No response received after 5 attempts")
            return

        print(f"Response length: {len(response)} bytes\n")

        # Find DataVendorStatusReq in the raw data and extract its status fields
        # The response may contain multiple concatenated messages

        # Look for the status message pattern
        status_marker = b'DataVendorStatusReq'
        if status_marker in response:
            # Find where the status data starts
            idx = response.find(status_marker)
            # The status data follows - scan for field 10 marker
            # Field 10 with wire type 2 (length-delimited) = (10 << 3) | 2 = 82 = 0x52

            # Extract a chunk around the marker for parsing
            chunk_start = max(0, idx - 50)
            chunk = response[chunk_start:]

            # Try to find and parse the embedded message
            # Look for 'R' (0x52) which is field 10 marker
            r_idx = chunk.find(b'R', len(status_marker))
            if r_idx > 0:
                # Skip the 'R' and length byte(s)
                data_start = r_idx + 1
                # Read the length
                length = chunk[data_start]
                data_start += 1
                if length & 0x80:  # Multi-byte varint
                    length = (length & 0x7F) | (chunk[data_start] << 7)
                    data_start += 1

                status_data = chunk[data_start:data_start + length]
                status_fields = ProtobufDecoder.decode_message(status_data)

                print("=== STATUS DATA (DataVendorStatusReq) ===")
                for field_num, value in sorted(status_fields.items()):
                    if isinstance(value, bytes):
                        try:
                            decoded = value.decode('utf-8')
                            print(f"  Field {field_num}: {decoded} (string)")
                        except:
                            print(f"  Field {field_num}: <bytes> len={len(value)}")
                    elif isinstance(value, float):
                        print(f"  Field {field_num}: {value:.2f} (float)")
                    else:
                        print(f"  Field {field_num}: {value}")
        else:
            print("DataVendorStatusReq not found in response")

            # Fall back to standard parsing
            outer_fields = ProtobufDecoder.decode_message(response)
            print("\n=== OUTER FIELDS ===")
            for field_num, value in sorted(outer_fields.items()):
                if isinstance(value, bytes):
                    print(f"  Field {field_num}: <bytes> len={len(value)}")
                else:
                    print(f"  Field {field_num}: {value}")

        # Also check field 4 for device info
        if 4 in outer_fields and isinstance(outer_fields[4], bytes):
            device_info = ProtobufDecoder.decode_message(outer_fields[4])
            print("\n=== FIELD 4 (device info) ===")
            for field_num, value in sorted(device_info.items()):
                if isinstance(value, bytes):
                    try:
                        decoded = value.decode('utf-8')
                        print(f"  Field {field_num}: {decoded}")
                    except:
                        print(f"  Field {field_num}: <bytes> len={len(value)}")
                else:
                    print(f"  Field {field_num}: {value}")

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

if __name__ == "__main__":
    main()
