# #region Test.Git.RemoteProviders.Coverage [C:3] [TYPE Module] [SEMANTICS test, git, remote, coverage, error, json]
# @BRIEF Additional edge coverage for GitServiceRemoteMixin — JSON parse exception branches in GitLab create/mr.
# @RELATION BINDS_TO -> [GitServiceRemoteMixin]

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "src"))

from unittest.mock import AsyncMock, MagicMock

import pytest
from fastapi import HTTPException

from src.services.git._remote_providers import GitServiceGitlabMixin


class TestableGitGitlab(GitServiceGitlabMixin):
    def __init__(self):
        self._http_client = AsyncMock()

    def _normalize_git_server_url(self, raw_url):
        return (raw_url or "").strip().rstrip("/")

    def _parse_remote_repo_identity(self, remote_url):
        from urllib.parse import urlparse
        normalized = str(remote_url or "").strip()
        path = urlparse(normalized).path.strip("/")
        if path.endswith(".git"):
            path = path[:-4]
        parts = [s for s in path.split("/") if s]
        owner, repo = parts[0], parts[-1]
        namespace = "/".join(parts[:-1])
        return {"owner": owner, "repo": repo, "namespace": namespace, "full_name": f"{namespace}/{repo}"}


class TestGitLabCreateRepoCoverage:
    """Cover JSON parse exception in create_gitlab_repository."""

    @pytest.mark.asyncio
    async def test_error_response_json_parse_raises(self):
        """API error, JSON parse fails → uses raw text."""
        svc = TestableGitGitlab()
        resp = MagicMock()
        resp.status_code = 400
        resp.text = "Bad Request"
        resp.json.side_effect = ValueError("no json")
        svc._http_client.post.return_value = resp

        with pytest.raises(HTTPException, match="Bad Request"):
            await svc.create_gitlab_repository("https://gitlab.com", "pat", "repo")


class TestGitLabCreateMRCoverage:
    """Cover JSON parse exception in create_gitlab_merge_request."""

    @pytest.mark.asyncio
    async def test_error_response_json_parse_raises(self):
        """API error, JSON parse fails → uses raw text."""
        svc = TestableGitGitlab()
        resp = MagicMock()
        resp.status_code = 400
        resp.text = "Bad Request"
        resp.json.side_effect = ValueError("no json")
        svc._http_client.post.return_value = resp

        with pytest.raises(HTTPException, match="Bad Request"):
            await svc.create_gitlab_merge_request(
                "https://gitlab.com", "pat",
                "https://gitlab.com/org/repo.git",
                "feature", "main", "Title",
            )
# #endregion Test.Git.RemoteProviders.Coverage
