from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, HTTPException, Path, Query, Request, status

from app.dependencies import AuthDep, Fail2BanConfigDirDep, Fail2BanSocketDep
from app.exceptions import (
    ConfigWriteError,
    FilterAlreadyExistsError,
    FilterInvalidRegexError,
    FilterNameError,
    FilterNotFoundError,
    FilterReadonlyError,
)
from app.models.config import (
    FilterConfig,
    FilterCreateRequest,
    FilterListResponse,
    FilterUpdateRequest,
)
from app.services import filter_config_service

router: APIRouter = APIRouter(prefix="/filters", tags=["Filter Config"])

_NamePath = Annotated[
    str,
    Path(description='Jail name as configured in fail2ban.'),
]

_FilterNamePath = Annotated[
    str,
    Path(description='Filter base name, e.g. ``sshd`` or ``sshd.conf``.'),
]


def _filter_not_found(name: str) -> HTTPException:
    return HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail=f"Filter not found: {name!r}",
    )


def _bad_request(message: str) -> HTTPException:
    return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=message)


def _unprocessable(message: str) -> HTTPException:
    return HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=message)


def _not_found(name: str) -> HTTPException:
    return HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail=f"Jail not found: {name!r}",
    )

@router.get(
    "",
    response_model=FilterListResponse,
    summary="List all available filters with active/inactive status",
)
async def list_filters(
    request: Request,
    _auth: AuthDep,
    config_dir: Fail2BanConfigDirDep,
    socket_path: Fail2BanSocketDep,
) -> FilterListResponse:
    """Return all filters discovered in ``filter.d/`` with active/inactive status.

    Scans ``{config_dir}/filter.d/`` for ``.conf`` files, merges any
    corresponding ``.local`` overrides, and cross-references each filter's
    name against the ``filter`` fields of currently running jails to determine
    whether it is active.

    Active filters (those used by at least one running jail) are sorted to the
    top of the list; inactive filters follow.  Both groups are sorted
    alphabetically within themselves.

    Args:
        request: FastAPI request object.
        _auth: Validated session — enforces authentication.

    Returns:
        :class:`~app.models.config.FilterListResponse` with all discovered
        filters.
    """
    result = await filter_config_service.list_filters(config_dir, socket_path)
    # Sort: active first (by name), then inactive (by name).
    result.filters.sort(key=lambda f: (not f.active, f.name.lower()))
    return result




@router.get(
    "/{name}",
    response_model=FilterConfig,
    summary="Return full parsed detail for a single filter",
)
async def get_filter(
    request: Request,
    _auth: AuthDep,
    config_dir: Fail2BanConfigDirDep,
    socket_path: Fail2BanSocketDep,
    name: Annotated[str, Path(description="Filter base name, e.g. ``sshd`` or ``sshd.conf``.")],
) -> FilterConfig:
    """Return the full parsed configuration and active/inactive status for one filter.

    Reads ``{config_dir}/filter.d/{name}.conf``, merges any corresponding
    ``.local`` override, and annotates the result with ``active``,
    ``used_by_jails``, ``source_file``, and ``has_local_override``.

    Args:
        request: FastAPI request object.
        _auth: Validated session — enforces authentication.
        name: Filter base name (with or without ``.conf`` extension).

    Returns:
        :class:`~app.models.config.FilterConfig`.

    Raises:
        HTTPException: 404 if the filter is not found in ``filter.d/``.
        HTTPException: 502 if fail2ban is unreachable.
    """
    try:
        return await filter_config_service.get_filter(config_dir, socket_path, name)
    except FilterNotFoundError:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Filter not found: {name!r}",
        ) from None


# ---------------------------------------------------------------------------
# Filter write endpoints (Task 2.2)
# ---------------------------------------------------------------------------


_FilterNamePath = Annotated[
    str,
    Path(description="Filter base name, e.g. ``sshd`` or ``sshd.conf``."),
]


def _filter_not_found(name: str) -> HTTPException:
    return HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail=f"Filter not found: {name!r}",
    )




@router.put(
    "/{name}",
    response_model=FilterConfig,
    summary="Update a filter's .local override with new regex/pattern values",
)
async def update_filter(
    request: Request,
    _auth: AuthDep,
    config_dir: Fail2BanConfigDirDep,
    socket_path: Fail2BanSocketDep,
    name: _FilterNamePath,
    body: FilterUpdateRequest,
    reload: bool = Query(default=False, description="Reload fail2ban after writing."),
) -> FilterConfig:
    """Update a filter's ``[Definition]`` fields by writing a ``.local`` override.

    All regex patterns are validated before writing.  The original ``.conf``
    file is never modified.  Fields left as ``null`` in the request body are
    kept at their current values.

    Args:
        request: FastAPI request object.
        _auth: Validated session.
        name: Filter base name (with or without ``.conf`` extension).
        body: Partial update — ``failregex``, ``ignoreregex``, ``datepattern``,
              ``journalmatch``.
        reload: When ``true``, trigger a fail2ban reload after writing.

    Returns:
        Updated :class:`~app.models.config.FilterConfig`.

    Raises:
        HTTPException: 400 if *name* contains invalid characters.
        HTTPException: 404 if the filter does not exist.
        HTTPException: 422 if any regex pattern fails to compile.
        HTTPException: 500 if writing the ``.local`` file fails.
    """
    try:
        return await filter_config_service.update_filter(config_dir, socket_path, name, body, do_reload=reload)
    except FilterNameError as exc:
        raise _bad_request(str(exc)) from exc
    except FilterNotFoundError:
        raise _filter_not_found(name) from None
    except FilterInvalidRegexError as exc:
        raise _unprocessable(str(exc)) from exc
    except ConfigWriteError as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to write filter override: {exc}",
        ) from exc




@router.post(
    "",
    response_model=FilterConfig,
    status_code=status.HTTP_201_CREATED,
    summary="Create a new user-defined filter",
)
async def create_filter(
    request: Request,
    _auth: AuthDep,
    config_dir: Fail2BanConfigDirDep,
    socket_path: Fail2BanSocketDep,
    body: FilterCreateRequest,
    reload: bool = Query(default=False, description="Reload fail2ban after creating."),
) -> FilterConfig:
    """Create a new user-defined filter at ``filter.d/{name}.local``.

    The filter is created as a ``.local`` file so it can coexist safely with
    shipped ``.conf`` files.  Returns 409 if a ``.conf`` or ``.local`` for
    the requested name already exists.

    Args:
        request: FastAPI request object.
        _auth: Validated session.
        body: Filter name and ``[Definition]`` fields.
        reload: When ``true``, trigger a fail2ban reload after creating.

    Returns:
        :class:`~app.models.config.FilterConfig` for the new filter.

    Raises:
        HTTPException: 400 if the name contains invalid characters.
        HTTPException: 409 if the filter already exists.
        HTTPException: 422 if any regex pattern is invalid.
        HTTPException: 500 if writing fails.
    """
    try:
        return await filter_config_service.create_filter(config_dir, socket_path, body, do_reload=reload)
    except FilterNameError as exc:
        raise _bad_request(str(exc)) from exc
    except FilterAlreadyExistsError as exc:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"Filter {exc.name!r} already exists.",
        ) from exc
    except FilterInvalidRegexError as exc:
        raise _unprocessable(str(exc)) from exc
    except ConfigWriteError as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to write filter: {exc}",
        ) from exc




@router.delete(
    "/{name}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="Delete a user-created filter's .local file",
)
async def delete_filter(
    request: Request,
    _auth: AuthDep,
    config_dir: Fail2BanConfigDirDep,
    name: _FilterNamePath,
) -> None:
    """Delete a user-created filter's ``.local`` override file.

    Shipped ``.conf``-only filters cannot be deleted (returns 409).  When
    both a ``.conf`` and a ``.local`` exist, only the ``.local`` is removed.
    When only a ``.local`` exists (user-created filter), the file is deleted
    entirely.

    Args:
        request: FastAPI request object.
        _auth: Validated session.
        name: Filter base name.

    Raises:
        HTTPException: 400 if *name* contains invalid characters.
        HTTPException: 404 if the filter does not exist.
        HTTPException: 409 if the filter is a shipped default (conf-only).
        HTTPException: 500 if deletion fails.
    """
    try:
        await filter_config_service.delete_filter(config_dir, name)
    except FilterNameError as exc:
        raise _bad_request(str(exc)) from exc
    except FilterNotFoundError:
        raise _filter_not_found(name) from None
    except FilterReadonlyError as exc:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=str(exc),
        ) from exc
    except ConfigWriteError as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete filter: {exc}",
        ) from exc




# ---------------------------------------------------------------------------
# Action discovery endpoints (Task 3.1)
# ---------------------------------------------------------------------------

_ActionNamePath = Annotated[
    str,
    Path(description="Action base name, e.g. ``iptables`` or ``iptables.conf``."),
]


def _action_not_found(name: str) -> HTTPException:
    return HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail=f"Action not found: {name!r}",
    )




