#!/usr/bin/env python3
"""Log delegation script - Serial type (UART).

Reads log data from UART daemon's log files.
The daemon must be running to collect new logs.
"""

import sys
import tomllib
from pathlib import Path


def main() -> int:
    """Read UART log from daemon's log files.

    Returns:
        0 on success, 1 on error
    """
    project_root = Path.cwd()
    config_path = project_root / ".fwauto" / "config.toml"

    if not config_path.exists():
        print(f"Error: Config not found: {config_path}", file=sys.stderr)
        return 1

    with open(config_path, "rb") as f:
        config = tomllib.load(f)

    # Read log section config
    log_config = config.get("log", {})
    serial_port = log_config.get("serial_port", "")

    if not serial_port:
        print("Error: Serial port not configured", file=sys.stderr)
        print("Tip: Run 'fwauto config --log' to configure", file=sys.stderr)
        return 1

    # Find latest UART log file
    log_dir = project_root / ".fwauto" / "logs"
    if not log_dir.exists():
        print("Error: No log directory found", file=sys.stderr)
        print("Tip: Run 'fwauto uart start' to begin UART monitoring", file=sys.stderr)
        return 1

    log_files = sorted(log_dir.glob("uart_*.log"), reverse=True)
    if not log_files:
        print("Error: No UART log files found", file=sys.stderr)
        print("Tip: Run 'fwauto uart start' to begin UART monitoring", file=sys.stderr)
        return 1

    latest_log = log_files[0]

    # Check if daemon is running
    pid_file = project_root / ".fwauto" / "uart.pid"
    daemon_running = False
    if pid_file.exists():
        try:
            import os

            pid = int(pid_file.read_text().strip())
            os.kill(pid, 0)  # Check if process exists
            daemon_running = True
        except (ValueError, OSError):
            pass

    # Output log info header
    print(f"# UART Log: {latest_log.name}", file=sys.stderr)
    print(f"# Port: {serial_port}", file=sys.stderr)
    print(f"# Daemon: {'running' if daemon_running else 'stopped'}", file=sys.stderr)
    print(f"# Size: {latest_log.stat().st_size} bytes", file=sys.stderr)
    print("#" + "=" * 40, file=sys.stderr)

    # Output log contents to stdout (for log_node to analyze)
    try:
        content = latest_log.read_text(encoding="utf-8", errors="replace")
        print(content)
        return 0
    except OSError as e:
        print(f"Error: Failed to read log file: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
