"""Settings views."""

from __future__ import annotations

from sqlalchemy import select as sa_select
from starlette.requests import Request
from starlette.responses import RedirectResponse
from starlette.responses import Response

from fenliu.config import settings
from fenliu.database import get_db
from fenliu.logging import get_logger
from fenliu.models import AppSetting
from fenliu.models import BlockedHashtag
from fenliu.models import BlockedUser
from fenliu.services.api_key import get_api_key
from fenliu.services.blocklist_cache import get_bool_setting
from fenliu.services.blocklist_cache import invalidate_cache
from fenliu.templates_env import templates

logger = get_logger(__name__)


async def settings_page(request: Request) -> Response:
    """Render the settings management page."""
    with get_db() as db:
        blocked_users = list(db.execute(sa_select(BlockedUser).order_by(BlockedUser.created_at.desc())).scalars().all())
        blocked_hashtags = list(
            db.execute(sa_select(BlockedHashtag).order_by(BlockedHashtag.created_at.desc())).scalars().all()
        )

        # Get API key if it exists
        api_key = get_api_key(db)

        context = {
            "blocked_users": blocked_users,
            "blocked_hashtags": blocked_hashtags,
            "attachments_only": get_bool_setting(db, "attachments_only"),
            "auto_reject_on_fetch": get_bool_setting(db, "auto_reject_blocked"),
            "auto_reject_bots": get_bool_setting(db, "auto_reject_bots"),
            "app_name": settings.app_name,
            "app_version": settings.app_version,
            "api_key": api_key or "",
        }
        return templates.TemplateResponse(request, "settings.html", context)


async def update_settings(request: Request) -> Response:
    """Handle form submission for updating reblog settings."""
    try:
        form_data = await request.form()
        logger.debug(f"Form data received: {dict(form_data)}")
        with get_db() as db:
            # Helper to set boolean settings
            def _set_bool_setting(key: str, value: bool) -> None:
                row = db.execute(sa_select(AppSetting).where(AppSetting.key == key)).scalar_one_or_none()
                if row is None:
                    db.add(AppSetting(key=key, value=str(value).lower()))
                else:
                    row.value = str(value).lower()
                logger.debug(f"Set {key} to {value}")

            # Update settings from form data - checkboxes return "on" when checked
            attachments_only = form_data.get("attachments_only") == "on"
            auto_reject_on_fetch = form_data.get("auto_reject_on_fetch") == "on"
            auto_reject_bots = form_data.get("auto_reject_bots") == "on"
            logger.debug(
                f"Parsed settings: attachments_only={attachments_only}, "
                f"auto_reject_on_fetch={auto_reject_on_fetch}, auto_reject_bots={auto_reject_bots}"
            )

            _set_bool_setting("attachments_only", attachments_only)
            _set_bool_setting("auto_reject_blocked", auto_reject_on_fetch)
            _set_bool_setting("auto_reject_bots", auto_reject_bots)
            db.commit()
            invalidate_cache()
            logger.info(
                f"Settings updated: attachments_only={attachments_only}, "
                f"auto_reject_on_fetch={auto_reject_on_fetch}, auto_reject_bots={auto_reject_bots}"
            )

        # Redirect back to settings page
        return RedirectResponse(url="/settings", status_code=303)
    except Exception as e:
        logger.error(f"Error updating settings: {e}", exc_info=True)
        return RedirectResponse(url="/settings", status_code=303)
