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

import subprocess
import sys
import tomllib
from pathlib import Path


def main() -> int:
    """Fetch log via SSH."""
    project_root = Path.cwd()
    config_path = project_root / ".fwauto" / "config.toml"

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

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

    # 讀取 deployment 設定（與 deploy 共用）
    deployment = config.get("deployment", {})
    board_ip = deployment.get("board_ip")
    board_user = deployment.get("board_user", "root")

    if not board_ip:
        print("❌ deployment.board_ip not configured", file=sys.stderr)
        return 1

    # 讀取 log 設定
    log_config = config.get("log", {})
    remote_path = log_config.get("remote_path", "/var/log/syslog")
    lines = log_config.get("lines", 100)

    # SSH 抓取日誌
    ssh_cmd = [
        "ssh",
        f"{board_user}@{board_ip}",
        f"tail -n {lines} {remote_path}",
    ]
    print(f"📋 Fetching log: {' '.join(ssh_cmd)}")

    result = subprocess.run(ssh_cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"❌ SSH error: {result.stderr}", file=sys.stderr)
        return result.returncode

    print(result.stdout)
    return 0


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