"""
Settings routes: PyGitWeb global options, PyGit2 library settings, and per-project git config.
Forms are generated from type() and docstrings; project config shows only LOCAL/WORKTREE entries.
"""

from __future__ import annotations

import os
from contextlib import suppress
from typing import Any
from urllib.parse import quote

import pygit2
from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse, RedirectResponse

from pygitweb.auth import require_permission
from pygitweb.config import settings
from pygitweb.dependencies import ValidatedSettingsProject
from pygitweb.permissions import Permission
from pygitweb.settings_config import settings_batch_update
from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env, jinja_escape


def _quote_path(path: str) -> str:
	"""Quote path segment for URL (e.g. project name with slashes)."""
	return quote(path, safe="/")


# libgit2 config levels: only local (5) and worktree (6) for per-repo editing
GIT_CONFIG_LEVEL_LOCAL = 5
GIT_CONFIG_LEVEL_WORKTREE = 6

router = APIRouter(
	prefix="/settings",
	tags=["settings"],
	dependencies=[Depends(require_permission(Permission.SETTINGS))],
)


# ---------- PyGitWeb settings schema ----------
# Name, type, docstring for form generation. Must match Settings field names.
PYGITWEB_SETTINGS: list[tuple[str, type, str]] = [
	("PROJECTROOT", str, "Root filesystem path under which git repositories live."),
	("PROJECTS_LIST", str, "Path used for listing projects (often same as PROJECTROOT)."),
	("SITE_NAME", str, "Site name shown in the web interface."),
	("EXPORT_OK", str, "If set, only repos with this file (or matching path) are listed."),
	("LIST_ALL", bool, "When true, list all directories under project root without export_ok checks."),
	("STRICT_EXPORT", bool, "When true, require export_ok (or path match) to list projects."),
	("GIT", str, "Path to the git executable (e.g. for maintenance)."),
	("MAXLOAD", float, "Max load average; 503 when exceeded. Empty to disable."),
]


def _get_pygitweb_values() -> list[tuple[str, Any, type, str]]:
	"""Return (name, current_value, type, docstring) for each PyGitWeb setting."""
	return [(name, getattr(settings, name), expected_type, doc) for name, expected_type, doc in PYGITWEB_SETTINGS]


def _render_form_field(name: str, value: Any, value_type: type, docstring: str, name_prefix: str = "") -> str:
	"""Generate HTML for a single form field based on type."""
	field_name = f"{name_prefix}{name}" if name_prefix else name
	safe_name = field_name.replace(".", "_")
	tpl = env.get_template("settings_form_field.html")
	if value_type is bool:
		return tpl.render(
			kind="bool",
			safe_name=safe_name,
			field_name=field_name,
			name=name,
			checked=bool(value),
			hint_text=docstring,
		)
	if value_type in (int, float):
		raw = "" if value is None else str(value)
		return tpl.render(
			kind="number",
			safe_name=safe_name,
			field_name=field_name,
			name=name,
			str_val=raw,
			hint_text=docstring,
			number_step="any",
		)
	raw = "" if value is None else str(value)
	return tpl.render(
		kind="text",
		safe_name=safe_name,
		field_name=field_name,
		name=name,
		str_val=raw,
		hint_text=docstring,
	)


# ---------- PyGit2 Settings schema ----------
# List of (attr_name, docstring, value_kind: 'bool'|'int'|'str'|'readonly').
# Based on https://www.pygit2.org/settings.html
PYGIT2_SETTINGS = [
	(
		"cache_max_size",
		"Maximum total data size (bytes) cached in memory across all repositories. Default 256MB.",
		"int",
	),
	(
		"cache_object_limit",
		"Max size per object type for caching (use cache_object_limit_commit etc. for fine-grained).",
		"skip",
	),  # multi-param
	(
		"cached_memory",
		"Current bytes in cache and maximum allowed (read-only).",
		"readonly",
	),
	(
		"disable_pack_keep_file_checks",
		"Skip .keep file checks when accessing packfiles; can help on remote filesystems.",
		"bool",
	),
	("enable_caching", "Enable or disable caching completely.", "bool"),
	(
		"enable_fsync_gitdir",
		"Enable or disable fsync for git directory operations.",
		"bool",
	),
	(
		"enable_http_expect_continue",
		"Enable or disable HTTP Expect/Continue for large pushes.",
		"bool",
	),
	("enable_ofs_delta", "Enable or disable offset delta encoding.", "bool"),
	(
		"enable_strict_hash_verification",
		"Enable or disable strict hash verification.",
		"bool",
	),
	(
		"enable_strict_object_creation",
		"Enable or disable strict object creation validation.",
		"bool",
	),
	(
		"enable_strict_symbolic_ref_creation",
		"Enable or disable strict symbolic reference creation validation.",
		"bool",
	),
	(
		"enable_unsaved_index_safety",
		"Enable or disable unsaved index safety checks.",
		"bool",
	),
	("extensions", "List of enabled extensions (read-only).", "readonly"),
	("homedir", "Home directory for config lookup.", "str"),
	("mwindow_file_limit", "Maximum number of files to be mapped at any time.", "int"),
	(
		"mwindow_mapped_limit",
		"Maximum memory that will be mapped in total by the library.",
		"int",
	),
	("mwindow_size", "Maximum mmap window size.", "int"),
	(
		"owner_validation",
		"Validate that repository directories are owned by the current user.",
		"bool",
	),
	("pack_max_objects", "Maximum number of objects in a pack.", "int"),
	("search_path", "Configuration file search path (read-only).", "readonly"),
	("server_connect_timeout", "Server connection timeout in milliseconds.", "int"),
	("server_timeout", "Server timeout in milliseconds.", "int"),
	("ssl_cert_dir", "TLS certificates lookup directory path.", "str"),
	("ssl_cert_file", "TLS certificate file path.", "str"),
	("template_path", "Default template path for new repositories.", "str"),
	("user_agent", "User agent string for network operations.", "str"),
	("user_agent_product", "User agent product name.", "str"),
	("windows_sharemode", "Windows share mode for opening files.", "int"),
]


def _get_pygit2_values() -> list[tuple[str, Any, str, str]]:
	"""Return (name, value, kind, docstring) for each PyGit2 setting we can show."""
	st = pygit2.Settings
	instance = pygit2.Settings()  # need instance to read property values
	out = []
	for attr, docstring, kind in PYGIT2_SETTINGS:
		if kind == "skip":
			continue
		if not hasattr(st, attr):
			continue
		try:
			prop = getattr(st, attr)
			if callable(prop) and not isinstance(prop, property):
				continue
			val = getattr(instance, attr)
			if isinstance(val, (list, tuple)):
				val = ", ".join(str(x) for x in val) if val else ""
			elif val is None:
				val = ""
			out.append((attr, val, kind, docstring))
		except (TypeError, AttributeError):
			continue
	return out


def _render_pygit2_field(name: str, value: Any, kind: str, docstring: str, name_prefix: str = "pygit2_") -> str:
	"""Generate HTML for a PyGit2 form field."""
	field_name = f"{name_prefix}{name}"
	safe_name = field_name.replace(".", "_")
	tpl = env.get_template("settings_form_field.html")
	if kind == "readonly":
		raw = str(value) if value != "" else "(not set)"
		return tpl.render(
			kind="readonly",
			safe_name=safe_name,
			field_name=field_name,
			name=name,
			str_val=raw,
			hint_text=docstring,
		)
	if kind == "bool":
		checked_attr = (
			" checked"
			if (value is True or (isinstance(value, str) and value.lower() in ("true", "1", "on", "yes")))
			else ""
		)
		return tpl.render(
			kind="bool",
			safe_name=safe_name,
			field_name=field_name,
			name=name,
			checked=(checked_attr != ""),
			hint_text=docstring,
		)
	if kind == "int":
		raw = str(value) if value != "" and value is not None else ""
		return tpl.render(
			kind="number",
			safe_name=safe_name,
			field_name=field_name,
			name=name,
			str_val=raw,
			hint_text=docstring,
		)
	raw = str(value) if value is not None else ""
	return tpl.render(
		kind="text",
		safe_name=safe_name,
		field_name=field_name,
		name=name,
		str_val=raw,
		hint_text=docstring,
	)


# ---------- Project config (local/worktree only) ----------
def _get_project_config_entries(project: str) -> list[tuple[str, str]]:
	"""
	Return list of (name, value) for repo config, only from LOCAL (5) or WORKTREE (6).
	For each name we keep the last value (highest priority when iterating).
	"""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	cfg = repo.config
	# Iterate; for level in (5, 6) keep last value per name
	by_name: dict[str, str] = {}
	for entry in cfg:
		if entry.level not in (GIT_CONFIG_LEVEL_LOCAL, GIT_CONFIG_LEVEL_WORKTREE):
			continue
		by_name[entry.name] = entry.value or ""
	return [(k, v) for k, v in sorted(by_name.items())]


def _project_config_table_row(key: str, value: str, index: int) -> list[str]:
	"""One table row as [key_cell_html, value_cell_html] for project config form."""
	key_name = f"config_key_{index}"
	val_name = f"config_value_{index}"
	key_cell = (
		'<input type="text" class="form-control form-control-sm" '
		f'id="{key_name}" name="{key_name}" '
		f'value="{jinja_escape(key)}" placeholder="e.g. user.name">'
	)
	val_cell = (
		'<input type="text" class="form-control form-control-sm" '
		f'id="{val_name}" name="{val_name}" '
		f'value="{jinja_escape(value)}" placeholder="value">'
	)
	return [key_cell, val_cell]


# ---------- Routes: PyGitWeb ----------
@router.get("/pygitweb", response_class=HTMLResponse)
def settings_pygitweb_page(request: Request):
	"""PyGitWeb global settings form."""
	fields_html = []
	for name, val, value_type, doc in _get_pygitweb_values():
		fields_html.append(_render_form_field(name, val, value_type, doc))
	form_body = "\n".join(fields_html)
	pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - PyGitWeb settings", site_name=settings.SITE_NAME)
	body = env.get_template("pygitweb_settings.html").render(form_body=form_body)
	return HTMLResponse(f"{pre}{body}{POSTAMBLE}")


@router.post("/pygitweb/submit", response_class=HTMLResponse)
async def settings_pygitweb_submit(request: Request):
	"""Apply PyGitWeb settings and persist to the settings JSON file."""
	form = await request.form()

	def _get(k: str) -> str:
		return str(form.get(k) or "").strip()

	_TRUTHY = {"on", "1", "true", "yes"}
	with settings_batch_update(settings):
		for name, expected_type, _doc in PYGITWEB_SETTINGS:
			raw = _get(name)
			if expected_type is bool:
				setattr(settings, name, raw.lower() in _TRUTHY)
			elif expected_type is float:
				with suppress(ValueError):
					setattr(settings, name, float(raw) if raw else None)
			elif raw:
				setattr(settings, name, raw)
	return RedirectResponse(url="/settings/pygitweb", status_code=303)


# ---------- Routes: PyGit2 ----------
@router.get("/pygit2", response_class=HTMLResponse)
def settings_pygit2_page(request: Request):
	"""PyGit2 library settings form."""
	fields_html = []
	for name, val, kind, doc in _get_pygit2_values():
		fields_html.append(_render_pygit2_field(name, val, kind, doc))
	form_body = "\n".join(fields_html)
	pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - PyGit2 settings", site_name=settings.SITE_NAME)
	body = env.get_template("pygit2_settings.html").render(form_body=form_body)
	return HTMLResponse(f"{pre}{body}{POSTAMBLE}")


@router.post("/pygit2/submit", response_class=HTMLResponse)
async def settings_pygit2_submit(request: Request):
	"""Apply PyGit2 settings from form (all pygit2_* fields)."""
	form = await request.form()
	st = pygit2.Settings
	for key, form_value in form.items():
		if not key.startswith("pygit2_"):
			continue
		attr = key[7:]  # strip pygit2_
		if attr not in [x[0] for x in PYGIT2_SETTINGS]:
			continue
		kind = next((k[2] for k in PYGIT2_SETTINGS if k[0] == attr), "str")
		if kind in ("readonly", "skip"):
			continue
		try:
			if kind == "bool":
				_ = str(form_value or "").strip().lower() in ("on", "1", "true", "yes")
				setattr(st, attr, _)
			elif kind == "int":
				s = str(form_value or "").strip()
				_ = int(s) if s else 0
				setattr(st, attr, _)
			else:
				setattr(st, attr, str(form_value).strip() if form_value else None)
		except (TypeError, AttributeError, ValueError):
			continue
	return RedirectResponse(url="/settings/pygit2", status_code=303)


# ---------- Routes: Project ----------
@router.get("/project/{name:path}", response_class=HTMLResponse)
def settings_project_page(request: Request, name: ValidatedSettingsProject):
	"""Project-specific git config form (local/worktree only)."""
	entries = _get_project_config_entries(name)
	rows = [_project_config_table_row(k, v, i) for i, (k, v) in enumerate(entries)]
	# One empty row for adding new
	rows.append(_project_config_table_row("", "", len(entries)))
	table_html = env.get_template("table.html").render(cols=["Key", "Value"], rows=rows)
	pre = PREAMBLE.render(
		title=f"{settings.SITE_NAME} - Project settings: {name}",
		site_name=settings.SITE_NAME,
	)
	submit_url = f"/settings/project/{_quote_path(name)}/submit"
	cancel_url = f"/project/{_quote_path(name)}"
	body = env.get_template("project_settings.html").render(
		project_title=name,
		submit_url=submit_url,
		cancel_url=cancel_url,
		table_html=table_html,
	)
	return HTMLResponse(f"{pre}{body}{POSTAMBLE}")


@router.post("/project/{name:path}/submit", response_class=HTMLResponse)
async def settings_project_submit(request: Request, name: ValidatedSettingsProject):
	"""Apply project config from form."""
	form = await request.form()
	# Collect key/value pairs; keys are config_key_0, config_value_0, ...
	indices = set()
	for form_key in form:
		if form_key.startswith("config_key_"):
			with suppress(ValueError):
				indices.add(int(form_key.split("_")[-1]))
	pairs = []
	for i in sorted(indices):
		k = str(form.get(f"config_key_{i}") or "").strip() or ""
		v = str(form.get(f"config_value_{i}") or "").strip() or ""
		if k:
			pairs.append((k, v))
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, name))
	cfg = repo.config
	for config_key, config_value in pairs:
		try:
			cfg[config_key] = config_value
		except (pygit2.GitError, ValueError, KeyError):
			continue
	return RedirectResponse(url=f"/settings/project/{_quote_path(name)}", status_code=303)