#!/usr/bin/env python3
"""
Neurotron — ponto de entrada do “cérebro” do NFDOS.
Boot flow: init (BusyBox) → Python → Neurotron (este ficheiro).
"""

import os
import sys
import time
import json
from datetime import datetime
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.pretty import pprint

from neurotron_core import neurotron_config
from neurotron_core.autodiagnostic import AutoDiagnostic
from neurotron_core.perception import Perception
from neurotron_core.neurotron_config import (
    NEUROTRON_TICK, NEUROTRON_MODE, NEUROTRON_HOMEOSTASIS,
    CORTEX_LOOP_DELAY, MOTOR_OUTPUT_DEVICE, BASE_DIR, CORE_DIR
)

console = Console()

# Caminho base do Neurotron
if not CORE_DIR.exists():
    console.print(f"[red]Erro:[/] diretório esperado não encontrado: {CORE_DIR}")
    sys.exit(1)
if str(CORE_DIR) not in sys.path:
    sys.path.insert(0, str(CORE_DIR))

console.print("[cyan]🧩 Mapa Neural de Importação:[/cyan]")
for p in sys.path:
    console.print(f" - {p}")

from neurotron_core.cortex import Cortex  # noqa: E402


def detect_persistent_mount() -> bool:
    """Verifica se o hipocampo físico está montado em /var/neurotron"""
    mount_point = Path("/var/neurotron")
    try:
        if mount_point.exists() and os.path.ismount(mount_point):
            console.print(f"[green]💾 Hipocampo físico montado:[/] {mount_point}")
            return True
        else:
            # fallback: check by /proc/mounts in early boot
            with open("/proc/mounts") as f:
                for line in f:
                    if " /var/neurotron " in line:
                        console.print(f"[green]💾 Hipocampo físico montado (via /proc):[/] {mount_point}")
                        return True
    except Exception as e:
        console.print(f"[yellow]⚠ Falha ao verificar montagem persistente:[/] {e}")
    return False


def main():
    persistent_mode = detect_persistent_mount()
    if persistent_mode:
        os.environ["NEUROTRON_MODE"] = "persistent"
        os.environ["NEUROTRON_RUNTIME"] = "/var/neurotron/data"
        os.environ["NEUROTRON_LOG"] = "/var/neurotron/logs"
    else:
        os.environ["NEUROTRON_MODE"] = "volatile"
        os.environ["NEUROTRON_RUNTIME"] = "/tmp/neurotron_data"
        os.environ["NEUROTRON_LOG"] = "/tmp/neurotron_logs"

    runtime_dir = Path(os.environ["NEUROTRON_RUNTIME"])
    log_dir = Path(os.environ["NEUROTRON_LOG"])
    runtime_dir.mkdir(parents=True, exist_ok=True)
    log_dir.mkdir(parents=True, exist_ok=True)

    mode = os.environ["NEUROTRON_MODE"]
    console.print(f"[cyan]🌍 Modo atual do Neurotron:[/] [bold]{mode.upper()}[/]")

    # inicializa o Córtex
    cortex = Cortex(runtime_dir=runtime_dir, log_dir=log_dir, tick_seconds=NEUROTRON_TICK)

    try:
        cortex.boot()
        state = cortex.diagnostic._load_previous().get("state", "?")
        console.print(f"[cyan]🩺 Estado inicial:[/] {state}\n")
        console.print("[green]👉 Neurotron inicializado com sucesso.[/]\n")
        console.print("[green]✔ [Mensagem Simbolica] Boot OK[/]\n")

        console.print("[green]✔ Iniciando ciclo cognitivo.[/]\n")
        while True:
            cortex.observe()
            cortex.think()
            cortex.act()
            cortex.rest()

    except KeyboardInterrupt:
        console.print("[yellow]⚠ Interrompido pelo utilizador (SIGINT)[/]")
        cortex.shutdown(reason="SIGINT")

    except SystemExit:
        cortex.shutdown(reason="SystemExit")

    except Exception as e:
        console.print(f"[red]💥 Exceção não tratada:[/] {e}")
        cortex.fatal(e)


if __name__ == "__main__":
    main()

