from __future__ import annotations

from collections.abc import Generator
from pathlib import Path
from unittest.mock import patch

import pygit2
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from pygittools.merge import MR_REF_PREFIX, MergeRequest
from pygitweb.auth import ACCESS_TOKEN_COOKIE_NAME
from pygitweb.auth_config import AuthConfig, LocalUser
from pygitweb.config import settings
from pygitweb.conftest import client_as_user
from pygitweb.merge_requests import merge_router
from pygitweb.permissions import Permission, PermissionsMap, permission_key
from pygitweb.sessions import create_session


def _commit_chain(repo: pygit2.Repository) -> tuple[pygit2.Oid, pygit2.Oid]:
	sig = pygit2.Signature("tester", "tester@example.com")
	tb = repo.TreeBuilder()
	tree = tb.write()
	a = repo.create_commit(None, sig, sig, "a", tree, [])
	repo.create_reference("refs/heads/main", a)
	b = repo.create_commit(None, sig, sig, "b", tree, [a])
	return a, b


_MR_AUTH = AuthConfig(
	auth_mode="local",
	local_users=[LocalUser(user="creator", password="secret"), LocalUser(user="merger", password="secret")],
	oauth_permissions=PermissionsMap.model_validate({
		"*": [],
		permission_key(Permission.MR_CREATE, "demo"): ["creator", "creator@idp.example"],
		permission_key(Permission.MR_MERGE, "demo"): ["merger"],
	}),
)


def _build_client() -> TestClient:
	app = FastAPI()
	app.include_router(merge_router, prefix="/mr")
	return TestClient(app)


@pytest.fixture
def mr_env(tmp_path: Path) -> Generator[dict[str, str], None, None]:
	root = tmp_path / "mr-perms"
	root.mkdir()
	repo_dir = root / "demo"
	repo_dir.mkdir()
	repo = pygit2.init_repository(str(repo_dir), bare=False)
	_a, b = _commit_chain(repo)
	mr = MergeRequest(
		b,
		pygit2.Signature("tester", "tester@example.com"),
		ours="refs/heads/main",
		title="Feature MR",
		name=f"{MR_REF_PREFIX}aaaabbbbccccdddd",
	)
	mr_oid = mr.write(repo)
	projects_list = root / "projects.list"
	projects_list.write_text("demo tester\n", encoding="utf-8")
	with (
		patch.object(settings, "PROJECTROOT", str(root)),
		patch.object(settings, "PROJECTS_LIST", str(projects_list)),
		patch.object(settings, "STRICT_EXPORT", False),
		patch.object(settings, "EXPORT_OK", ""),
		patch("pygitweb.auth_config.auth_config", _MR_AUTH),
		patch("pygitweb.auth.auth_config", _MR_AUTH),
	):
		yield {
			"client": _build_client(),
			"project": "demo",
			"mr_tag_oid": str(mr_oid),
			"tip_b": str(b),
		}


def test_mr_ff_open_when_auth_disabled(mr_env: dict[str, str]) -> None:
	client = mr_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", False):
		r = client.post(
			"/mr/ff",
			params={"project": mr_env["project"], "h": mr_env["mr_tag_oid"]},
			follow_redirects=False,
		)
	assert r.status_code == 303


def test_mr_create_401_without_login(mr_env: dict[str, str]) -> None:
	client = mr_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True):
		r = client.post(
			"/mr/create",
			data={
				"project": mr_env["project"],
				"theirs": "refs/heads/main",
				"ours": "refs/heads/main",
				"title": "MR",
			},
			follow_redirects=False,
		)
	assert r.status_code == 401


def test_mr_create_forbidden_without_create_grant(mr_env: dict[str, str]) -> None:
	client = mr_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True), client_as_user(client, "merger"):
		r = client.post(
			"/mr/create",
			data={
				"project": mr_env["project"],
				"theirs": "refs/heads/main",
				"ours": "refs/heads/main",
				"title": "MR",
			},
			follow_redirects=False,
		)
	assert r.status_code == 403


def test_mr_ff_forbidden_without_merge_grant(mr_env: dict[str, str]) -> None:
	client = mr_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True), client_as_user(client, "creator"):
		r = client.post(
			"/mr/ff",
			params={"project": mr_env["project"], "h": mr_env["mr_tag_oid"]},
			follow_redirects=False,
		)
	assert r.status_code == 403


def test_mr_ff_allowed_with_merge_grant(mr_env: dict[str, str]) -> None:
	client = mr_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True), client_as_user(client, "merger"):
		r = client.post(
			"/mr/ff",
			params={"project": mr_env["project"], "h": mr_env["mr_tag_oid"]},
			follow_redirects=False,
		)
	assert r.status_code == 303


def _bare_repo_with_branch(tmp_path: Path) -> tuple[Path, pygit2.Oid, pygit2.Oid]:
	root = tmp_path / "bare-mr-create"
	root.mkdir()
	repo_dir = root / "demo"
	repo = pygit2.init_repository(str(repo_dir), bare=True)
	a, b = _commit_chain(repo)
	repo.create_reference("refs/heads/feature", b)
	return root, a, b


def test_mr_create_bare_repo_uses_principal_email(tmp_path: Path) -> None:
	root, _a, _b = _bare_repo_with_branch(tmp_path)
	projects_list = root / "projects.list"
	projects_list.write_text("demo tester\n", encoding="utf-8")
	client = _build_client()
	with (
		patch.object(settings, "PROJECTROOT", str(root)),
		patch.object(settings, "PROJECTS_LIST", str(projects_list)),
		patch.object(settings, "STRICT_EXPORT", False),
		patch.object(settings, "EXPORT_OK", ""),
		patch("pygitweb.auth_config.auth_config", _MR_AUTH),
		patch("pygitweb.auth.auth_config", _MR_AUTH),
		patch.object(settings, "AUTH", True),
	):
		client.cookies.set(
			ACCESS_TOKEN_COOKIE_NAME,
			create_session("creator", email="creator@idp.example", auth_method="local"),
		)
		r = client.post(
			"/mr/create",
			data={
				"project": "demo",
				"theirs": "refs/heads/feature",
				"ours": "refs/heads/main",
				"title": "Bare MR",
			},
			follow_redirects=False,
		)
	assert r.status_code == 303
	location = r.headers["location"]
	assert "notice=" not in location
	repo = pygit2.Repository(str(root / "demo"))
	for ref_name in repo.references:
		if ref_name.startswith("refs/tags/mr/"):
			tag = repo[repo.references[ref_name].resolve().target]
			assert isinstance(tag, pygit2.Tag)
			assert tag.tagger is not None
			assert tag.tagger.email == "creator@idp.example"
			return
	raise AssertionError("merge request tag not created")


def test_mr_create_bare_repo_without_identity_shows_notice(tmp_path: Path) -> None:
	root, _a, _b = _bare_repo_with_branch(tmp_path)
	projects_list = root / "projects.list"
	projects_list.write_text("demo tester\n", encoding="utf-8")
	client = _build_client()
	with (
		patch.object(settings, "PROJECTROOT", str(root)),
		patch.object(settings, "PROJECTS_LIST", str(projects_list)),
		patch.object(settings, "STRICT_EXPORT", False),
		patch.object(settings, "EXPORT_OK", ""),
		patch.object(settings, "AUTH", False),
	):
		r = client.post(
			"/mr/create",
			data={
				"project": "demo",
				"theirs": "refs/heads/feature",
				"ours": "refs/heads/main",
				"title": "Bare MR",
			},
			follow_redirects=False,
		)
	assert r.status_code == 303
	assert "notice=" in r.headers["location"]