"""Fixtures for the opt-in Docker/local Gitea integration suite (#66).

Everything here is inert unless GITEA_INTEGRATION=1 — the test modules carry
a module-level skipif, so a default ``pytest tests/ -q`` run never touches the
network and never needs Docker.

Required environment (see tests/integration/README.md):
- GITEA_INTEGRATION=1                 opt-in switch
- GITEA_INTEGRATION_URL               base URL (default http://localhost:3003)
- GITEA_INTEGRATION_TOKEN             API token for the *local test* instance

The token is a throwaway credential for the disposable container. It is never
printed, logged, or asserted on. Production credentials must never be used.
"""
import os
import sys
import uuid
from pathlib import Path

import pytest

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

from gitea_auth import api_request  # noqa: E402

ENABLED = os.environ.get("GITEA_INTEGRATION") == "1"


def _base_url():
    return os.environ.get("GITEA_INTEGRATION_URL", "http://localhost:3003").rstrip("/")


@pytest.fixture(scope="session")
def gitea():
    """Session facts: base URL, auth header string, authenticated login."""
    token = os.environ.get("GITEA_INTEGRATION_TOKEN")
    if not token:
        pytest.fail(
            "GITEA_INTEGRATION=1 but GITEA_INTEGRATION_TOKEN is unset; "
            "run tests/integration/gitea-integration token"
        )
    base = _base_url()
    auth = f"token {token}"
    me = api_request("GET", f"{base}/api/v1/user", auth)
    return {"base": base, "auth": auth, "login": me["login"]}


@pytest.fixture(scope="session")
def seed_repo(gitea):
    """Create a disposable, uniquely-named repo; delete it on teardown."""
    name = f"inttest-{uuid.uuid4().hex[:8]}"
    repo = api_request(
        "POST", f"{gitea['base']}/api/v1/user/repos", gitea["auth"],
        payload={"name": name, "auto_init": True,
                 "description": "gitea-tools #66 integration seed (disposable)"},
    )
    owner = repo["owner"]["login"]
    yield {"owner": owner, "name": name,
           "api": f"{gitea['base']}/api/v1/repos/{owner}/{name}"}
    # Teardown: best-effort delete; a leaked repo is visible and disposable.
    try:
        api_request("DELETE", f"{gitea['base']}/api/v1/repos/{owner}/{name}",
                    gitea["auth"])
    except RuntimeError:
        pass
