"""テスト用にシンボリックリンク・ジャンクションを作る補助（push の送信対象からリンクを除くテスト）.

リンクはすべて tmp_path の中に作り，リンク先も tmp_path の中に置く（リポジトリの外の実在の
フォルダ・`legacy/`・`data/` を指さない）．作れない環境では pytest.skip する．

- シンボリックリンク: Windows では権限（開発者モード等）が無いと作れない（WinError 1314）
- ジャンクション: Windows で `cmd /c mklink /J` が使える場合だけ．それ以外の OS では skip
"""

from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

import pytest


class LinkFactory:
    """リンクを作り，後始末でジャンクションのリンクだけを外す（リンク先は消さない）."""

    def __init__(self) -> None:
        self._junctions: list[Path] = []

    def symlink(self, link: Path, target: Path, *, is_dir: bool | None = None) -> Path:
        """link → target のシンボリックリンクを作る（作れなければ skip）."""
        link.parent.mkdir(parents=True, exist_ok=True)
        directory = target.is_dir() if is_dir is None else is_dir
        try:
            os.symlink(target, link, target_is_directory=directory)
        except (OSError, NotImplementedError) as exc:
            code = getattr(exc, "winerror", None) or getattr(exc, "errno", None)
            pytest.skip(f"この環境ではシンボリックリンクを作れない（{type(exc).__name__} {code}）")
        return link

    def junction(self, link: Path, target: Path) -> Path:
        """link → target のジャンクションを作る（Windows で作れなければ skip）."""
        if sys.platform != "win32":
            pytest.skip("ジャンクションは Windows のみ")
        link.parent.mkdir(parents=True, exist_ok=True)
        try:
            result = subprocess.run(
                ["cmd", "/c", "mklink", "/J", str(link), str(target)],
                capture_output=True,
                check=False,
            )
        except OSError as exc:
            pytest.skip(f"mklink を実行できない: {exc}")
        if result.returncode != 0 or not os.path.isjunction(link):
            pytest.skip("この環境ではジャンクションを作れない")
        self._junctions.append(link)
        return link

    def cleanup(self) -> None:
        """ジャンクションを外す（tmp_path の後始末がリンク先をたどって消さないように）."""
        for link in reversed(self._junctions):
            if os.path.isjunction(link):
                os.rmdir(link)
        self._junctions.clear()
