#!/usr/bin/env python3
"""
Neurotron — entrypoint oficial.
Arranque do dashboard + thread cognitiva.
Totalmente silencioso fora do LogBus.
"""

import sys
import threading
import time
import traceback
from pathlib import Path

from neurotron.logbus import logbus
from neurotron.cortex import Cortex
from neurotron.dashboard.renderer import Renderer


# =============================================================================
# DASHBOARD (modo texto minimalista)
# =============================================================================

def dashboard_loop(ctx: Cortex):
    renderer = Renderer()

    while True:
        renderer.render(ctx)
        time.sleep(0.1)

# =============================================================================
# CICLO COGNITIVO
# =============================================================================

def cognitive_loop(ctx: Cortex):
    """Loop cognitivo principal (observe → think → act → rest)."""
    try:
        ctx.boot()
        logbus.info("Ciclo cognitivo iniciado (observe → think → act → rest)")

        while True:
            ctx.observe()   # sensores, discos, vitals
            ctx.think()     # neurónios decidem
            ctx.act()       # motor executa
            ctx.rest()      # heartbeat + diag + sleep

    except Exception as e:
        logbus.error(f"Fatal no ciclo cognitivo: {repr(e)}")

        tb = traceback.format_exc()
        for line in tb.splitlines():
            logbus.error(line)

        ctx.shutdown("fatal exception")
        raise

# =============================================================================
# MAIN
# =============================================================================

def main():
    """
    Entrada principal do Neurotron.
    Inicia:
      - cortex
      - dashboard (thread)
      - ciclo cognitivo (thread)
    """

    runtime_dir = "/opt/kernel/neurotron/runtime"
    log_dir     = "/opt/kernel/neurotron/logs"

    Path(runtime_dir).mkdir(parents=True, exist_ok=True)
    Path(log_dir).mkdir(parents=True, exist_ok=True)

    ctx = Cortex(runtime_dir=runtime_dir, log_dir=log_dir)

    # threads
    t_dash = threading.Thread(target=dashboard_loop, args=(ctx,), daemon=True)
    t_cog  = threading.Thread(target=cognitive_loop, args=(ctx,), daemon=True)

    t_dash.start()
    t_cog.start()

    # thread principal fica apenas a dormir
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logbus.warn("Interrompido pelo utilizador")
        ctx.shutdown("CTRL+C")


if __name__ == "__main__":
    main()

