#!/usr/bin/env python3
"""End-to-end chat message test.

Tests the full chat workflow by launching TUI in tmux and monitoring database:
1. Launch TUI in background tmux session
2. Wait for target node discovery
3. Verify LXMF capability in database
4. Report results

NOTE: This test launches a fresh TUI instance to avoid RNS singleton conflicts.
"""

import os
import sqlite3
import subprocess
import sys
import time
from pathlib import Path

# Configuration from environment
DISCOVERY_TIMEOUT = int(os.getenv("DISCOVERY_TIMEOUT", "40"))
TARGET_NAME = os.getenv("TARGET_NAME", "styrene-node")
PROJECT_ROOT = Path(__file__).parent.parent.parent
DB_PATH = Path.home() / "Library/Application Support/styrene/nodes.db"

print(f"=== Styrene Chat E2E Test ===\n")


def cleanup_tmux_session(session_name: str):
    """Kill tmux session if it exists."""
    subprocess.run(
        ["tmux", "kill-session", "-t", session_name],
        capture_output=True,
    )


def start_tui_in_tmux(session_name: str) -> bool:
    """Start TUI in a tmux session.

    Returns:
        True if started successfully, False otherwise.
    """
    try:
        result = subprocess.run(
            [
                "tmux",
                "new-session",
                "-d",
                "-s",
                session_name,
                f"cd {PROJECT_ROOT} && .venv/bin/python -m styrene",
            ],
            capture_output=True,
            text=True,
            check=True,
        )
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ Failed to start TUI: {e.stderr}")
        return False


def clear_old_node_data(destination_hash: str):
    """Remove old node entry from database."""
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "DELETE FROM nodes WHERE destination_hash = ?", (destination_hash,)
        )
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"Warning: Could not clear old data: {e}")


def wait_for_node_discovery(
    target_name: str, timeout: int
) -> tuple[str | None, str | None]:
    """Wait for target node to be discovered with LXMF capability.

    Args:
        target_name: Name of target node (e.g., "styrene-node")
        timeout: Maximum wait time in seconds

    Returns:
        Tuple of (destination_hash, lxmf_destination_hash) if found, (None, None) otherwise
    """
    start_time = time.monotonic()

    while (time.monotonic() - start_time) < timeout:
        try:
            conn = sqlite3.connect(DB_PATH)
            cursor = conn.execute(
                "SELECT destination_hash, lxmf_destination_hash FROM nodes WHERE name = ?",
                (target_name,),
            )
            row = cursor.fetchone()
            conn.close()

            if row and row[1]:  # Has LXMF destination
                return (row[0], row[1])

        except Exception as e:
            print(f"Database query error: {e}")

        # Wait and check again
        time.sleep(2)
        print(".", end="", flush=True)

    print()
    return (None, None)


def main() -> int:
    """Run end-to-end discovery test."""
    session_name = "styrene_e2e_test"

    # Clean up any existing sessions
    cleanup_tmux_session(session_name)

    # Clear old Q502 data if present
    Q502_DEST = "9e21f49afdaae8885663e807606387a2"
    clear_old_node_data(Q502_DEST)
    print("✓ Cleaned up old data")

    # Start TUI in tmux
    print("Starting TUI in background...")
    if not start_tui_in_tmux(session_name):
        return 1

    print("✓ TUI started")

    # Wait for services to initialize
    print("Waiting for services to initialize...", end="", flush=True)
    time.sleep(10)
    print(" done")

    # Wait for target node discovery
    print(
        f"Waiting for {TARGET_NAME} discovery (timeout: {DISCOVERY_TIMEOUT}s)...",
        end="",
        flush=True,
    )
    dest_hash, lxmf_hash = wait_for_node_discovery(TARGET_NAME, DISCOVERY_TIMEOUT)

    # Clean up tmux session
    cleanup_tmux_session(session_name)

    # Report results
    print()
    if dest_hash and lxmf_hash:
        print(f"✓ {TARGET_NAME} discovered!")
        print(f"  Destination: {dest_hash[:16]}...")
        print(f"  LXMF dest:   {lxmf_hash[:16]}...")
        print()
        print("✓ Test PASSED - Discovery successful")
        return 0
    else:
        print(f"✗ {TARGET_NAME} not discovered within timeout")
        print()
        print("✗ Test FAILED")
        return 1


if __name__ == "__main__":
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n\nTest interrupted by user")
        cleanup_tmux_session("styrene_e2e_test")
        sys.exit(1)
    except Exception as e:
        print(f"\n✗ Test failed with error: {e}")
        cleanup_tmux_session("styrene_e2e_test")
        sys.exit(1)
