"""
Authentication: local password login and OAuth2 authorization-code (browser).

FastAPI security integration
----------------------------
- ``OAuth2PasswordBearer`` + ``APIKeyCookie``: extract PyGitWeb's opaque session id from
  ``Authorization: Bearer`` or the login cookie. This is *not* an IdP JWT; OpenAPI still
  documents the password ``/token`` flow that mints these session ids.
- ``OAuth2PasswordRequestForm``: local ``POST /token`` only (resource-owner password grant).
- External IdP login (Google/GitHub) uses standard authorization-code redirects implemented
  in ``auth_oauth``; ``OAuth2AuthorizationCodeBearer`` is intentionally not used because
  clients never receive or send the provider's access token—only our session id.
"""

from __future__ import annotations

import hmac
from typing import Annotated

from fastapi import APIRouter, Depends, Form, HTTPException, Query, status
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.security import APIKeyCookie, OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel

from pygitweb.auth_config import (
	auth_config,
	is_auth_configured,
	is_local_auth_available,
	is_oauth_auth_available,
)
from pygitweb.auth_oauth import OAUTH_STATE_COOKIE_NAME, oauth_router
from pygitweb.config import settings
from pygitweb.permissions import Permission, PermissionPrincipal
from pygitweb.sessions import create_session, get_session, revoke_session
from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env

ACCESS_TOKEN_COOKIE_NAME = "pygitweb_access_token"
LOGIN_COOKIE_MAX_AGE = 60 * 60 * 24 * 7

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
_access_token_cookie = APIKeyCookie(name=ACCESS_TOKEN_COOKIE_NAME, auto_error=False)

TAG_AUTH = "auth"
TAG_AUTH_LOCAL = "auth - local"
TAG_AUTH_OAUTH = "auth - OAuth"

auth_router = APIRouter()
auth_router.include_router(oauth_router)


class User(BaseModel):
	username: str
	email: str | None = None


def principal_from_session(token: str | None) -> PermissionPrincipal | None:
	if not token:
		return None
	rec = get_session(token)
	if rec is None:
		return None
	return PermissionPrincipal(username=rec.username, email=rec.email)


def has_permission(
	permission: Permission,
	project: str | None = None,
	*,
	token: str | None = None,
) -> bool:
	if not settings.AUTH:
		return True
	principal = principal_from_session(token)
	if principal is None:
		return False
	return auth_config.oauth_permissions.has_permission(principal.identity, permission, project)


def ensure_permission(
	permission: Permission,
	project: str | None = None,
	*,
	token: str | None,
) -> None:
	ensure_active_user_if_auth_enabled(token)
	if has_permission(permission, project, token=token):
		return
	raise HTTPException(
		status_code=status.HTTP_403_FORBIDDEN,
		detail="Insufficient permissions",
	)


def require_permission(
	permission: Permission,
	*,
	project_from_query: bool = False,
	project_from_form: bool = False,
) -> object:
	"""Return a FastAPI dependency that enforces ``permission`` when auth is enabled."""

	if project_from_query:

		def _dep_query_project(
			token: Annotated[str | None, Depends(access_token_from_request)],
			project: Annotated[str, Query()],
		) -> None:
			ensure_permission(permission, project, token=token)

		return _dep_query_project

	if project_from_form:

		def _dep_form_project(
			token: Annotated[str | None, Depends(access_token_from_request)],
			project: Annotated[str, Form()],
		) -> None:
			ensure_permission(permission, project, token=token)

		return _dep_form_project

	def _dep(
		token: Annotated[str | None, Depends(access_token_from_request)],
	) -> None:
		ensure_permission(permission, None, token=token)

	return _dep


class UserInDB(User):
	password: str


def get_local_user(username: str) -> UserInDB | None:
	if not settings.AUTH or not is_local_auth_available(auth_config):
		return None
	for entry in auth_config.local_users:
		if not entry.password:
			continue
		if hmac.compare_digest(entry.user, username):
			return UserInDB(username=entry.user, password=entry.password)
	return None


def authenticate_local_user(username: str, password: str) -> User | None:
	if auth_config.auth_mode not in ("local", "both"):
		return None
	user = get_local_user(username)
	if user is None:
		return None
	if not hmac.compare_digest(user.password, password):
		return None
	return User(username=user.username)


def decode_access_token(token: str) -> User | None:
	if not settings.AUTH:
		return None
	rec = get_session(token)
	if rec is None:
		return None
	return User(username=rec.username)


def safe_next_url(next_raw: str | None) -> str:
	n = (next_raw or "/").strip()
	if not n.startswith("/") or n.startswith("//"):
		return "/"
	return n


def access_token_from_request(
	bearer: Annotated[str | None, Depends(oauth2_scheme)],
	cookie_token: Annotated[str | None, Depends(_access_token_cookie)],
) -> str | None:
	b = bearer.strip() if bearer else None
	c = cookie_token.strip() if cookie_token else None
	return b or c


def ensure_active_user_if_auth_enabled(token: str | None) -> None:
	if not settings.AUTH:
		return
	if not is_auth_configured(auth_config):
		raise HTTPException(
			status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
			detail="Authentication enabled but auth.json is not configured",
		)
	if not token:
		raise HTTPException(
			status_code=status.HTTP_401_UNAUTHORIZED,
			detail="Not authenticated",
			headers={"WWW-Authenticate": "Bearer"},
		)
	if decode_access_token(token) is None:
		raise HTTPException(
			status_code=status.HTTP_401_UNAUTHORIZED,
			detail="Not authenticated",
			headers={"WWW-Authenticate": "Bearer"},
		)


def require_active_user_if_auth_enabled(
	token: Annotated[str | None, Depends(access_token_from_request)],
) -> None:
	ensure_active_user_if_auth_enabled(token)


@auth_router.get(
	"/login",
	response_class=HTMLResponse,
	tags=[TAG_AUTH],
	summary="Sign-in page",
	description="HTML sign-in page. Shows local and/or OAuth options depending on auth.json.",
)
async def login_page(
	next: Annotated[str, Query()] = "/",
) -> HTMLResponse:
	if not settings.AUTH:
		raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
	next_safe = safe_next_url(next)
	pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Sign in", site_name=settings.SITE_NAME)
	body = env.get_template("login.html").render(
		site_name=settings.SITE_NAME,
		next=next_safe,
		error=None,
		local_available=is_local_auth_available(auth_config),
		oauth_available=is_oauth_auth_available(auth_config),
		oauth_provider=str(auth_config.oauth_provider).strip() or "OAuth",
	)
	return HTMLResponse(f"{pre}{body}{POSTAMBLE}")


@auth_router.post(
	"/login",
	response_model=None,
	tags=[TAG_AUTH_LOCAL],
	summary="Local sign-in (form)",
	description="Browser form login. Sets the pygitweb_access_token session cookie on success.",
	responses={303: {"description": "Redirect to next URL with session cookie set"}},
)
async def login_form_submit(
	username: Annotated[str, Form()],
	password: Annotated[str, Form()],
	next: Annotated[str, Form()] = "/",
) -> HTMLResponse | RedirectResponse:
	if not settings.AUTH:
		raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
	if not is_local_auth_available(auth_config):
		raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Local sign-in is not enabled")
	next_safe = safe_next_url(next)
	user = authenticate_local_user(username.strip(), password)
	if user is None:
		pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Sign in", site_name=settings.SITE_NAME)
		body = env.get_template("login.html").render(
			site_name=settings.SITE_NAME,
			next=next_safe,
			error="Incorrect username or password.",
			local_available=True,
			oauth_available=is_oauth_auth_available(auth_config),
			oauth_provider=str(auth_config.oauth_provider).strip() or "OAuth",
		)
		return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
	sid = create_session(user.username, auth_method="local")
	resp = RedirectResponse(url=next_safe, status_code=303)
	resp.set_cookie(
		key=ACCESS_TOKEN_COOKIE_NAME,
		value=sid,
		httponly=True,
		samesite="lax",
		max_age=LOGIN_COOKIE_MAX_AGE,
		path="/",
	)
	return resp


@auth_router.get(
	"/logout",
	tags=[TAG_AUTH],
	summary="Sign out",
	description="Revokes the current session (cookie or Bearer) and clears auth cookies.",
	responses={303: {"description": "Redirect to next URL"}},
)
async def logout_page(
	token: Annotated[str | None, Depends(access_token_from_request)],
	next: Annotated[str, Query()] = "/",
) -> RedirectResponse:
	revoke_session(token)
	resp = RedirectResponse(url=safe_next_url(next), status_code=303)
	resp.delete_cookie(key=ACCESS_TOKEN_COOKIE_NAME, path="/")
	resp.delete_cookie(key=OAUTH_STATE_COOKIE_NAME, path="/")
	return resp


@auth_router.post(
	"/token",
	tags=[TAG_AUTH_LOCAL],
	summary="Obtain session token (local)",
	description=(
		"OAuth2 password flow for API clients. Returns an opaque session id as access_token; "
		"use Authorization: Bearer on protected routes. Not an identity-provider JWT."
	),
)
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]) -> dict[str, str]:
	if not settings.AUTH:
		raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
	if not is_local_auth_available(auth_config):
		raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Local sign-in is not enabled")
	user = authenticate_local_user(form_data.username, form_data.password)
	if user is None:
		raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect username or password")
	sid = create_session(user.username, auth_method="local")
	return {"access_token": sid, "token_type": "bearer"}


@auth_router.get(
	"/auth/status",
	tags=[TAG_AUTH],
	summary="Auth status (navbar)",
	description="Lightweight JSON for the navbar script. Does not return 401 when anonymous.",
)
async def auth_status(
	token: Annotated[str | None, Depends(access_token_from_request)],
) -> dict[str, bool | str | None]:
	if not settings.AUTH:
		return {"auth_enabled": False, "username": None}
	if not token:
		return {"auth_enabled": True, "username": None}
	u = decode_access_token(token)
	if u is None:
		return {"auth_enabled": True, "username": None}
	return {"auth_enabled": True, "username": u.username}


@auth_router.get(
	"/user",
	response_class=HTMLResponse,
	response_model=None,
	tags=[TAG_AUTH],
	summary="Account page",
	description="HTML account page for the signed-in user.",
)
async def user_account_page(
	token: Annotated[str | None, Depends(access_token_from_request)],
) -> HTMLResponse | RedirectResponse:
	if not settings.AUTH:
		pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Account", site_name=settings.SITE_NAME)
		body = '<p class="text-muted">Authentication is not enabled on this server.</p>'
		return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
	if not is_auth_configured(auth_config):
		raise HTTPException(
			status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
			detail="Authentication is misconfigured",
		)
	u = decode_access_token(token or "") if token else None
	if u is None:
		return RedirectResponse(url="/login?next=/user", status_code=303)
	pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Account", site_name=settings.SITE_NAME)
	body = env.get_template("user_profile.html").render(username=u.username, site_name=settings.SITE_NAME)
	return HTMLResponse(f"{pre}{body}{POSTAMBLE}")


@auth_router.get(
	"/users/me",
	response_model=User,
	tags=[TAG_AUTH],
	summary="Current user",
	description="Returns the username for the current session (cookie or Bearer).",
)
async def read_users_me(
	token: Annotated[str | None, Depends(access_token_from_request)],
) -> User:
	if not settings.AUTH:
		raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
	ensure_active_user_if_auth_enabled(token)
	u = decode_access_token(token or "")
	if u is None:
		raise HTTPException(
			status_code=status.HTTP_401_UNAUTHORIZED,
			detail="Not authenticated",
			headers={"WWW-Authenticate": "Bearer"},
		)
	return u