"""Tests for fliiq.runtime.security — credential path guards."""

import os
from pathlib import Path

import pytest

from fliiq.runtime.security import check_path_allowed

HOME = str(Path.home())


# --- Denied exact files ---


@pytest.mark.parametrize(
    "path",
    [
        os.path.join(HOME, ".fliiq", ".env"),
        os.path.join(HOME, ".fliiq", "google_tokens.json"),
        os.path.join(HOME, ".fliiq", "daemon.secret"),
    ],
)
def test_denied_files(path):
    with pytest.raises(PermissionError, match="protected credential file"):
        check_path_allowed(path)


# --- Denied directory prefixes ---


@pytest.mark.parametrize(
    "path",
    [
        os.path.join(HOME, ".ssh", "id_rsa"),
        os.path.join(HOME, ".ssh", "id_ed25519"),
        os.path.join(HOME, ".aws", "credentials"),
        os.path.join(HOME, ".aws", "config"),
        os.path.join(HOME, ".gnupg", "secring.gpg"),
    ],
)
def test_denied_prefixes(path):
    with pytest.raises(PermissionError, match="protected directory"):
        check_path_allowed(path)


# --- Denied directories themselves ---


@pytest.mark.parametrize(
    "path",
    [
        os.path.join(HOME, ".ssh"),
        os.path.join(HOME, ".aws"),
        os.path.join(HOME, ".gnupg"),
    ],
)
def test_denied_directory_roots(path):
    with pytest.raises(PermissionError, match="protected directory"):
        check_path_allowed(path)


# --- Allowed paths ---


@pytest.mark.parametrize(
    "path",
    [
        "/tmp/project/foo.py",
        os.path.join(HOME, "Documents", "project", "main.py"),
        os.path.join(HOME, ".fliiq", "jobs", "daily.yaml"),
        os.path.join(HOME, ".fliiq", "user.yaml"),
    ],
)
def test_allowed_paths(path):
    check_path_allowed(path)  # Should not raise


# --- Symlink bypass ---


def test_symlink_to_denied_file(tmp_path):
    """Symlink pointing to a denied file should still be denied."""
    target = os.path.join(HOME, ".fliiq", ".env")
    link = tmp_path / "sneaky_link"
    try:
        link.symlink_to(target)
    except OSError:
        pytest.skip("Cannot create symlink")

    with pytest.raises(PermissionError, match="protected credential file"):
        check_path_allowed(str(link))


def test_dotdot_bypass(tmp_path):
    """Path traversal with .. should still be denied."""
    traversal = os.path.join(HOME, ".fliiq", "jobs", "..", ".env")
    with pytest.raises(PermissionError, match="protected credential file"):
        check_path_allowed(traversal)


# --- Tilde expansion ---


def test_tilde_expansion():
    with pytest.raises(PermissionError, match="protected credential file"):
        check_path_allowed("~/.fliiq/.env")
