import os
import json
import pathlib

import pytest
from ecu_framework.config import load_config


@pytest.mark.unit
def test_config_precedence_env_overrides(monkeypatch, tmp_path, rp):
    # Create a YAML file to use via env var
    yaml_path = tmp_path / "cfg.yaml"
    yaml_path.write_text("interface:\n  type: babylin\n  channel: 7\n")

    # Point ECU_TESTS_CONFIG to env YAML
    monkeypatch.setenv("ECU_TESTS_CONFIG", str(yaml_path))

    # Apply overrides on top
    cfg = load_config(workspace_root=str(tmp_path), overrides={"interface": {"channel": 9}})
    rp("config_source", "env+overrides")
    rp("interface_type", cfg.interface.type)
    rp("interface_channel", cfg.interface.channel)

    # Env file applied
    assert cfg.interface.type == "babylin"
    # Overrides win
    assert cfg.interface.channel == 9


@pytest.mark.unit
def test_config_defaults_when_no_file(monkeypatch, rp):
    # Ensure no env path
    monkeypatch.delenv("ECU_TESTS_CONFIG", raising=False)

    cfg = load_config(workspace_root=None)
    rp("config_source", "defaults")
    rp("interface_type", cfg.interface.type)
    rp("flash_enabled", cfg.flash.enabled)
    assert cfg.interface.type == "mock"
    assert cfg.flash.enabled is False
