# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations

import pytest

from generate_cve_json.cve_json import _load_config

_DEFAULT_REL = ".apache-magpie-overrides/tools/cve-tool-vulnogram/cve-json-config.toml"
_LEGACY_REL = ".apache-magpie-overrides/tools/vulnogram/cve-json-config.toml"


def _write(root, relpath, vendor):
    p = root / relpath
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(f'vendor = "{vendor}"\n')
    return p


@pytest.fixture(autouse=True)
def _clean_env(monkeypatch, tmp_path):
    """Resolve config from the (empty) tmp cwd, with no env override."""
    monkeypatch.chdir(tmp_path)
    monkeypatch.delenv("CVE_JSON_CONFIG", raising=False)


def test_default_path_is_used_when_present(tmp_path, capsys):
    _write(tmp_path, _DEFAULT_REL, "New")
    assert _load_config() == {"vendor": "New"}
    assert "WARNING" not in capsys.readouterr().err


def test_legacy_path_used_with_warning_when_default_missing(tmp_path, capsys):
    _write(tmp_path, _LEGACY_REL, "Legacy")
    assert _load_config() == {"vendor": "Legacy"}
    err = capsys.readouterr().err
    assert "legacy path" in err
    assert "tools/cve-tool-vulnogram" in err  # points the adopter at the new path


def test_default_wins_over_legacy_when_both_present(tmp_path, capsys):
    _write(tmp_path, _DEFAULT_REL, "New")
    _write(tmp_path, _LEGACY_REL, "Legacy")
    assert _load_config() == {"vendor": "New"}
    assert "WARNING" not in capsys.readouterr().err


def test_missing_both_raises_pointing_at_the_new_path():
    with pytest.raises(FileNotFoundError) as exc:
        _load_config()
    assert "cve-tool-vulnogram" in str(exc.value)


def test_explicit_config_path_does_not_fall_back_to_legacy(tmp_path):
    # Legacy exists, but an explicit (missing) --config path must not silently
    # resolve to it — explicit intent wins and the error is surfaced.
    _write(tmp_path, _LEGACY_REL, "Legacy")
    with pytest.raises(FileNotFoundError):
        _load_config(tmp_path / "explicit-but-missing.toml")
