#!/usr/bin/env python3
"""Test script to check what the API actually returns"""
import sys
import json
from pathlib import Path
import re

# Add current directory to path
sys.path.insert(0, str(Path(__file__).parent))

LOGS_DIR = Path(__file__).parent / 'deployment' / 'logs'

def parse_log(content, node_num):
    """Parse log file content"""
    compression = 0
    match = re.search(r'Compression ratio:\s*([\d.]+)', content)
    if not match:
        match = re.search(r'Compression:\s*([\d.]+)', content)
    if match:
        compression = float(match.group(1))

    dna = 'N/A'
    match = re.search(r'DNA sequence:\s*(\w+)', content)
    if not match:
        match = re.search(r'DNA:\s*(\w+)', content)
    if match:
        dna = match.group(1)

    glyph = '?'
    match = re.search(r'Holographic glyph:\s*(.)', content)
    if not match:
        match = re.search(r'Glyph:\s*([^\s|]+)', content)
    if match:
        glyph = match.group(1)

    time_ms = 0
    match = re.search(r'Encoding time:\s*([\d.]+)\s*ms', content)
    if match:
        time_ms = float(match.group(1))

    error = 0
    match = re.search(r'Max errors:\s*k=([0-9.e+-]+)', content)
    if not match:
        match = re.search(r'Error:\s*k=([0-9.e+-]+)', content)
    if match:
        error = float(match.group(1))

    result = {
        'node': str(node_num),
        'active': compression > 0,
        'compression': compression,
        'dna': dna,
        'glyph': glyph,
        'time': time_ms,
        'error': error
    }

    print(f"\n--- Node {node_num} ---")
    print(f"Compression: {compression}")
    print(f"Active: {compression > 0} (compression > 0)")
    print(json.dumps(result, indent=2))

    return result

def test_all_nodes():
    """Test reading all node logs"""
    nodes = []
    max_nodes = 10

    print("=" * 60)
    print("Testing API Response Generation")
    print("=" * 60)

    for i in range(1, max_nodes + 1):
        log_file = LOGS_DIR / f"node{i}.log"
        if not log_file.exists():
            print(f"\nNode {i}: LOG NOT FOUND")
            continue

        print(f"\nNode {i}: {log_file} ({log_file.stat().st_size} bytes)")

        # Try UTF-16 first (WSL output), fallback to UTF-8
        content = None
        for encoding in ['utf-16', 'utf-8', 'latin-1']:
            try:
                with open(log_file, 'r', encoding=encoding, errors='ignore') as f:
                    content = f.read()
                if 'Compression ratio' in content or 'DNA sequence' in content:
                    print(f"  ✓ Encoding: {encoding}")
                    break
            except Exception as e:
                print(f"  ✗ Encoding {encoding} failed: {e}")
                continue

        if content:
            node_data = parse_log(content, i)
            nodes.append(node_data)
        else:
            print(f"  ERROR: Could not read content with any encoding!")

    print("\n" + "=" * 60)
    print(f"SUMMARY: {len(nodes)} nodes parsed")
    print("=" * 60)

    active_nodes = [n for n in nodes if n['active']]
    print(f"\nActive nodes: {len(active_nodes)}/{len(nodes)}")

    print("\n--- Final /api/nodes Response ---")
    print(json.dumps({'nodes': nodes}, indent=2))

    print("\n--- Final /api/status Response ---")
    status = {
        'nodes_total': len(nodes),
        'nodes_active': len(active_nodes),
        'avg_compression': sum(n['compression'] for n in active_nodes) / len(active_nodes) if active_nodes else 0,
        'dna_consensus': active_nodes[0]['dna'] if active_nodes else 'N/A',
    }
    print(json.dumps(status, indent=2))

if __name__ == '__main__':
    test_all_nodes()
