"""Interfaz básica en Flet para el dashboard de AGIX."""

from __future__ import annotations


if __package__ in {None, ""}:  # pragma: no cover - permite ejecución como script
    import sys
    from pathlib import Path

    _current_file = Path(__file__).resolve()
    for _parent in (_current_file.parent, *_current_file.parents):
        if (_parent / "pyproject.toml").exists() or (_parent / ".git").exists():
            _project_root = _parent
            break
    else:
        _project_root = _current_file.parents[2]
    _src_root = _project_root / "src"
    for _path in (_project_root, _src_root):
        _path_str = str(_path)
        if _path_str not in sys.path:
            sys.path.insert(0, _path_str)
    from agix._script_utils import bootstrap_script_environment

    bootstrap_script_environment("__main__", str(_current_file))

if __package__ in {None, ""}:  # pragma: no cover - habilita ejecución directa
    import importlib.util
    import sys
    from pathlib import Path

    current_file = Path(__file__).resolve()
    project_root = None
    for candidate in current_file.parents:
        if (candidate / "pyproject.toml").exists():
            project_root = candidate
            break
    if project_root is None:
        project_root = current_file.parents[3]

    helper_path = project_root / "src" / "agix" / "_script_utils.py"
    spec = importlib.util.spec_from_file_location("agix._script_utils", helper_path)
    if spec and spec.loader:
        module = sys.modules.get(spec.name)
        if module is None:
            module = importlib.util.module_from_spec(spec)
            sys.modules[spec.name] = module
            spec.loader.exec_module(module)
    else:  # pragma: no cover - sólo si falta el helper
        raise ImportError(f"No se pudo cargar el helper de scripts desde {helper_path}")

    sys.modules[spec.name].bootstrap_script_environment(__name__, __file__)

import flet as ft
import requests

from .styles import DEFAULT_THEME, style_button, style_container, style_text

DASHBOARD_URL = "http://localhost:8000"


def main(page: ft.Page) -> None:
    """Configura la página principal con componentes básicos."""
    page.title = "AGIX Dashboard"
    page.appbar = ft.AppBar(title=style_text(ft.Text("AGIX Dashboard"), DEFAULT_THEME))
    page.drawer = ft.NavigationDrawer(
        controls=[
            style_container(ft.Container(style_text(ft.Text("Inicio"), DEFAULT_THEME)), DEFAULT_THEME),
            style_container(ft.Container(style_text(ft.Text("Qualia"), DEFAULT_THEME)), DEFAULT_THEME),
            style_container(ft.Container(style_text(ft.Text("Métricas"), DEFAULT_THEME)), DEFAULT_THEME),
        ]
    )

    metrics_container = ft.Column()
    qualia_container = ft.Column()

    def refresh_metrics(_=None) -> None:
        try:
            data = requests.get(f"{DASHBOARD_URL}/metrics", timeout=5).json()
        except Exception as exc:  # pragma: no cover - manejo básico de errores
            data = {"error": str(exc)}
        metrics_container.controls = [
            style_text(ft.Text(f"{k}: {v}"), DEFAULT_THEME) for k, v in data.items()
        ]
        page.update()

    def refresh_qualia(_=None) -> None:
        try:
            data = requests.get(f"{DASHBOARD_URL}/qualia", timeout=5).json()
        except Exception as exc:  # pragma: no cover - manejo básico de errores
            data = {"emociones": {}, "tono": str(exc)}
        qualia_container.controls = [
            style_text(ft.Text(f"{k}: {v}"), DEFAULT_THEME)
            for k, v in data.get("emociones", {}).items()
        ]
        if "tono" in data:
            qualia_container.controls.append(
                style_text(ft.Text(f"tono: {data['tono']}"), DEFAULT_THEME)
            )
        page.update()

    page.add(
        ft.Column(
            [
                style_button(
                    ft.ElevatedButton("Actualizar Métricas", on_click=refresh_metrics),
                    DEFAULT_THEME,
                ),
                metrics_container,
                style_button(
                    ft.ElevatedButton("Actualizar Qualia", on_click=refresh_qualia),
                    DEFAULT_THEME,
                ),
                qualia_container,
            ]
        )
    )

    refresh_metrics()
    refresh_qualia()


if __name__ == "__main__":  # pragma: no cover
    ft.app(target=main)
