# #region TestGitServiceGiteaPr [C:2] [TYPE Module]
# @RELATION  BINDS_TO -> SrcRoot
# @SEMANTICS: tests, git, gitea, pull_request, fallback
# @PURPOSE: Validate Gitea PR creation fallback behavior when configured server URL is stale.
# @LAYER Domain
# @INVARIANT: A 404 from primary Gitea URL retries once against remote-url host when different.

import asyncio
from pathlib import Path
import pytest
import sys

from fastapi import HTTPException

sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from src.services.git_service import GitService


# #region test_derive_server_url_from_remote_strips_credentials [C:2] [TYPE Function]
# @RELATION  BINDS_TO -> TestGitServiceGiteaPr
# @PURPOSE: Ensure helper returns host base URL and removes embedded credentials.
# @PRE: remote_url is an https URL with username/token.
# @POST: Result is scheme+host only.
def test_derive_server_url_from_remote_strips_credentials():
    service = GitService(base_path="test_repos")
    derived = service._derive_server_url_from_remote(
        "https://oauth2:token@giteabusya.bebesh.ru/busya/covid-vaccine-dashboard.git"
    )
    assert derived == "https://giteabusya.bebesh.ru"
# #endregion test_derive_server_url_from_remote_strips_credentials


# #region test_create_gitea_pull_request_retries_with_remote_host_on_404 [C:2] [TYPE Function]
# @RELATION  BINDS_TO -> TestGitServiceGiteaPr
# @PURPOSE: Verify create_gitea_pull_request retries with remote URL host after primary 404.
# @PRE: primary server_url differs from remote_url host.
# @POST: Method returns success payload from fallback request.
def test_create_gitea_pull_request_retries_with_remote_host_on_404(monkeypatch):
    service = GitService(base_path="test_repos")
    calls = []

    async def fake_gitea_request(method, server_url, pat, endpoint, payload=None):
        calls.append((method, server_url, endpoint))
        if len(calls) == 1:
            raise HTTPException(status_code=404, detail="Gitea API error: The target couldn't be found.")
        return {"number": 42, "html_url": "https://giteabusya.bebesh.ru/busya/covid-vaccine-dashboard/pulls/42", "state": "open"}

    monkeypatch.setattr(service, "_gitea_request", fake_gitea_request)

    result = asyncio.run(
        service.create_gitea_pull_request(
            server_url="https://gitea.bebesh.ru",
            pat="secret",
            remote_url="https://oauth2:secret@giteabusya.bebesh.ru/busya/covid-vaccine-dashboard.git",
            from_branch="ss-dev",
            to_branch="main",
            title="Promote ss-dev -> main",
            description="",
        )
    )

    assert result["id"] == 42
    assert len(calls) == 2
    assert calls[0][1] == "https://gitea.bebesh.ru"
    assert calls[1][1] == "https://giteabusya.bebesh.ru"
# #endregion test_create_gitea_pull_request_retries_with_remote_host_on_404


# #region test_create_gitea_pull_request_returns_branch_error_when_target_missing [C:2] [TYPE Function]
# @RELATION  BINDS_TO -> TestGitServiceGiteaPr
# @PURPOSE: Ensure Gitea 404 on PR creation is mapped to actionable target-branch validation error.
# @PRE: PR create call returns 404 and target branch is absent.
# @POST: Service raises HTTPException 400 with explicit missing target branch message.
def test_create_gitea_pull_request_returns_branch_error_when_target_missing(monkeypatch):
    service = GitService(base_path="test_repos")

    async def fake_gitea_request(method, server_url, pat, endpoint, payload=None):
        if method == "POST" and endpoint.endswith("/pulls"):
            raise HTTPException(status_code=404, detail="Gitea API error: The target couldn't be found.")
        if method == "GET" and endpoint.endswith("/branches/dev"):
            return {"name": "dev"}
        if method == "GET" and endpoint.endswith("/branches/preprod"):
            raise HTTPException(status_code=404, detail="branch not found")
        raise AssertionError(f"Unexpected request: {method} {endpoint}")

    monkeypatch.setattr(service, "_gitea_request", fake_gitea_request)

    with pytest.raises(HTTPException) as exc_info:
        asyncio.run(
            service.create_gitea_pull_request(
                server_url="https://gitea.bebesh.ru",
                pat="secret",
                remote_url="https://gitea.bebesh.ru/busya/covid-vaccine-dashboard.git",
                from_branch="dev",
                to_branch="preprod",
                title="Promote dev -> preprod",
                description="",
            )
        )

    assert exc_info.value.status_code == 400
    assert "target branch 'preprod'" in str(exc_info.value.detail)
# #endregion test_create_gitea_pull_request_returns_branch_error_when_target_missing

# #endregion TestGitServiceGiteaPr
