"""
Web UI endpoints for serving the dashboard
"""

from fastapi import APIRouter
from fastapi.responses import HTMLResponse
from pathlib import Path
import logging

logger = logging.getLogger(__name__)

# Create router
router = APIRouter(prefix="", tags=["web-ui"])

# Get the web UI directory path
WEB_UI_DIR = Path(__file__).parent.parent.parent / "web_ui"
STATIC_DIR = WEB_UI_DIR / "static"
TEMPLATES_DIR = WEB_UI_DIR / "templates"

# Static files will be mounted in main.py

@router.get("/", response_class=HTMLResponse)
async def dashboard():
    """Serve the main dashboard page."""
    try:
        index_file = TEMPLATES_DIR / "index.html"

        if not index_file.exists():
            logger.error(f"Dashboard template not found: {index_file}")
            return HTMLResponse(
                content="<h1>Панель недоступна</h1><p>Не удалось найти шаблон веб-интерфейса.</p>",
                status_code=404
            )

        with open(index_file, 'r', encoding='utf-8') as f:
            content = f.read()

        return HTMLResponse(content=content)

    except Exception as e:
        logger.error(f"Error serving dashboard: {e}")
        return HTMLResponse(
            content=f"<h1>Ошибка</h1><p>Не удалось загрузить панель: {e}</p>",
            status_code=500
        )

@router.get("/health-ui")
async def health_ui():
    """Health check endpoint for web UI."""
    return {
        "service": "Веб-интерфейс VNA",
        "status": "работает",
        "web_ui_dir": str(WEB_UI_DIR),
        "static_dir_exists": STATIC_DIR.exists(),
        "templates_dir_exists": TEMPLATES_DIR.exists(),
        "index_exists": (TEMPLATES_DIR / "index.html").exists()
    }
