"""Atomic config writes + POSIX permission hardening."""

from __future__ import annotations

import os
import stat
import sys
import tempfile
from pathlib import Path

import pytest

from media_server.config import _restrict_config_perms, _write_yaml_atomic


def test_atomic_write_round_trip():
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / "config.yaml"
        _write_yaml_atomic(path, {"port": 8765, "host": "127.0.0.1"})
        assert path.exists()
        # Tmp file from the rename should be gone.
        assert not path.with_suffix(path.suffix + ".tmp").exists()
        # Contents are valid YAML and round-trip.
        import yaml
        data = yaml.safe_load(path.read_text())
        assert data == {"port": 8765, "host": "127.0.0.1"}


def test_atomic_write_replaces_existing():
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / "config.yaml"
        path.write_text("old: 1\n")
        _write_yaml_atomic(path, {"new": 2})
        import yaml
        assert yaml.safe_load(path.read_text()) == {"new": 2}


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only permission check")
def test_restrict_config_perms_posix():
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / "config.yaml"
        path.write_text("token: secret\n")
        _restrict_config_perms(path)
        mode = stat.S_IMODE(os.stat(path).st_mode)
        # Owner read+write only.
        assert mode == 0o600, f"got {oct(mode)}"
