"""Verify deployment of new features on 5.60"""
import paramiko
import json

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.5.60', username='ubains', password='Ubains@123')

def run(cmd):
    stdin, stdout, stderr = ssh.exec_command(cmd)
    return stdout.read().decode()

# Login
run('curl -s -c /tmp/cookie_test -X POST http://localhost:8088/login '
    '-H "Content-Type: application/json" '
    "-d '{ \"username\": \"admin\", \"password\": \"Ubains@1357\" }'")

# Get reports
reports_raw = run('curl -s -b /tmp/cookie_test http://localhost:8088/api/service-monitor/reports?limit=5')
d = json.loads(reports_raw)
reports = d.get('reports', [])
print(f'Found {len(reports)} reports')

if len(reports) >= 2:
    r1 = reports[0]['id']
    r2 = reports[1]['id']
    print(f'Testing: {r1} vs {r2}')

    # Test 1: Compare API
    cmp_raw = run(f'curl -s -b /tmp/cookie_test http://localhost:8088/api/service-monitor/reports/{r1}/compare/{r2}')
    cd = json.loads(cmp_raw)
    ok = cd.get('success')
    summary = cd.get('data', {}).get('diff_summary', {}) if ok else {}
    print(f'\n[TEST 1] Compare API: success={ok}')
    if ok:
        print(f'  new_abnormal={summary.get("new_abnormal")}, recovered={summary.get("recovered")}, value_changed={summary.get("value_changed")}')

    # Test 2: Excel export
    run(f'curl -s -b /tmp/cookie_test -o /tmp/test_excel.xlsx http://localhost:8088/api/service-monitor/reports/{r1}/export?format=excel')
    file_info = run('file /tmp/test_excel.xlsx')
    size_info = run('stat -c %s /tmp/test_excel.xlsx')
    print(f'\n[TEST 2] Excel Export: type={file_info.strip()}, size={size_info.strip()} bytes')

    # Test 3: PDF export
    run(f'curl -s -b /tmp/cookie_test -o /tmp/test_pdf.out http://localhost:8088/api/service-monitor/reports/{r1}/export?format=pdf')
    file_info = run('file /tmp/test_pdf.out')
    size_info = run('stat -c %s /tmp/test_pdf.out')
    is_pdf = file_info.strip().startswith('PDF document')
    print(f'\n[TEST 3] PDF Export: type={file_info.strip()}, size={size_info.strip()} bytes, is_pdf={is_pdf}')

    # Test 4: Compare export HTML
    run(f'curl -s -b /tmp/cookie_test -o /tmp/test_compare.html http://localhost:8088/api/service-monitor/reports/{r1}/compare/{r2}/export?format=html')
    size_info = run('stat -c %s /tmp/test_compare.html')
    head = run('head -1 /tmp/test_compare.html')
    print(f'\n[TEST 4] Compare Export HTML: size={size_info.strip()} bytes, starts_doctype={head.strip().startswith("<!DOCTYPE")}')

else:
    print(f'Only {len(reports)} reports, need >= 2')

ssh.close()
