"""Tests para dotenv_load."""

import os
import tempfile

import pytest

from dotenv_load import dotenv_load


def write_env(content: str) -> str:
    """Write content to a temp file and return its path."""
    fd, path = tempfile.mkstemp(suffix=".env")
    os.write(fd, content.encode())
    os.close(fd)
    return path


def _clean(*keys: str) -> None:
    for k in keys:
        os.environ.pop(k, None)


def test_parsea_key_value_y_setea_variable():
    path = write_env("DL_PY_FOO=hello\n")
    _clean("DL_PY_FOO")
    try:
        dotenv_load(path)
        assert os.environ.get("DL_PY_FOO") == "hello"
    finally:
        _clean("DL_PY_FOO")
        os.unlink(path)


def test_ignora_comentarios_y_lineas_vacias():
    content = "# comment\n\nDL_PY_BAR=world\n"
    path = write_env(content)
    _clean("DL_PY_BAR")
    try:
        dotenv_load(path)
        assert os.environ.get("DL_PY_BAR") == "world"
    finally:
        _clean("DL_PY_BAR")
        os.unlink(path)


def test_no_sobreescribe_variables_existentes():
    path = write_env("DL_PY_EXIST=new\n")
    os.environ["DL_PY_EXIST"] = "original"
    try:
        dotenv_load(path)
        assert os.environ["DL_PY_EXIST"] == "original"
    finally:
        _clean("DL_PY_EXIST")
        os.unlink(path)


def test_valores_con_comillas_dobles_se_stripean():
    path = write_env('DL_PY_QUOTED="quoted value"\n')
    _clean("DL_PY_QUOTED")
    try:
        dotenv_load(path)
        assert os.environ.get("DL_PY_QUOTED") == "quoted value"
    finally:
        _clean("DL_PY_QUOTED")
        os.unlink(path)


def test_valores_con_comillas_simples_se_stripean():
    path = write_env("DL_PY_SINGLE='single quoted'\n")
    _clean("DL_PY_SINGLE")
    try:
        dotenv_load(path)
        assert os.environ.get("DL_PY_SINGLE") == "single quoted"
    finally:
        _clean("DL_PY_SINGLE")
        os.unlink(path)


def test_archivo_inexistente_lanza_error():
    with pytest.raises(FileNotFoundError):
        dotenv_load("/nonexistent/.env.does.not.exist")


def test_linea_sin_igual_lanza_value_error():
    path = write_env("INVALID_LINE\n")
    try:
        with pytest.raises(ValueError, match="missing '='"):
            dotenv_load(path)
    finally:
        os.unlink(path)
