#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Data and I/O commands: post, relay, logs, brain export/import."""
from __future__ import annotations

import os
import subprocess
import sys

from pulse.cli import ROOT_DIR, STATE_DIR, TOOLS_DIR


def cmd_post(args: list[str]):
    """Post tasks to the board via relay (direct call, no subprocess)."""
    if not args:
        print('Usage: pulse post "Task title:domain:complexity"')
        print('Example: pulse post "Fix login bug:security:high"')
        return
    from pulse.tasks.pulse_relay import parse_manual_tasks  # noqa: E402
    from pulse.tasks.pulse_dispatcher import TaskDispatcher  # noqa: E402
    tasks = parse_manual_tasks(args)
    prompt = " + ".join(t["title"] for t in tasks)
    dispatcher = TaskDispatcher(verbose=True)
    dispatch_id = dispatcher.dispatch(prompt, tasks)
    print(f"[RELAY] Dispatched {len(tasks)} task(s) ({dispatch_id})")
    for t in tasks:
        print(f"  [{t['status']}] {t['task_id']}: {t['title']}")


def cmd_relay(args: list[str]):
    """Pass-through to pulse_relay.py."""
    relay = TOOLS_DIR / "pulse_relay.py"
    subprocess.run([sys.executable, str(relay)] + args)


def cmd_logs(args: list[str]):
    """Show worker logs."""
    logs_dir = STATE_DIR / "worker_logs"
    if not logs_dir.exists():
        print("[PULSE] No worker logs found.")
        return

    log_files = sorted(logs_dir.glob("*.log"), key=lambda x: x.stat().st_mtime)
    if not log_files:
        print("[PULSE] No worker logs found.")
        return

    target_log = None
    if args:
        worker_id = args[0]
        if not worker_id.endswith(".log"):
            worker_id += ".log"
        for f in log_files:
            if f.name == worker_id:
                target_log = f
                break
        if not target_log:
            print(f"[PULSE] Log file not found for worker: {args[0]}")
            print("Available logs:")
            for f in log_files:
                print(f"  - {f.name}")
            return
    else:
        target_log = log_files[-1]

    print(f"== Showing last 50 lines of {target_log.name} ==")
    try:
        with open(target_log, "r", encoding="utf-8", errors="replace") as f:
            lines = f.readlines()
            for line in lines[-50:]:
                print(line, end="")
    except Exception as e:
        print(f"Error reading log: {e}")


def cmd_brain_export(args: list[str]):
    """Export brain (Hippocampus + state) to a ZIP file."""
    import zipfile
    from datetime import datetime as dt

    dest = args[0] if args else f"pulse_brain_{dt.now().strftime('%Y%m%d_%H%M%S')}.zip"
    hippocampus = ROOT_DIR / "Hippocampus"
    if not hippocampus.exists():
        print("[PULSE] No Hippocampus directory found.")
        return

    count = 0
    with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as zf:
        for folder in [hippocampus, STATE_DIR]:
            if not folder.exists():
                continue
            for f in folder.rglob("*"):
                if f.is_file() and f.stat().st_size < 10_000_000:  # skip >10MB
                    arcname = f.relative_to(ROOT_DIR)
                    zf.write(f, arcname)
                    count += 1
    print(f"[PULSE] Exported {count} files to {dest}")


def cmd_brain_import(args: list[str]):
    """Import brain from a ZIP file (restores Hippocampus + state)."""
    import zipfile

    if not args:
        print("Usage: pulse brain import <file.zip>")
        return
    src = args[0]
    if not os.path.exists(src):
        print(f"[PULSE] File not found: {src}")
        return

    with zipfile.ZipFile(src, "r") as zf:
        # Safety: only extract Hippocampus/ and state/ paths
        safe = [m for m in zf.namelist()
                if m.startswith("Hippocampus/") or m.startswith("state/")]
        for name in safe:
            zf.extract(name, ROOT_DIR)
    print(f"[PULSE] Imported {len(safe)} files from {src}")
