# 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 json

from vulnogram_api import record_fetch
from vulnogram_api.client import record_body


def _write_session(path):
    path.write_text(
        json.dumps(
            {
                "host": "cveprocess.apache.org",
                "session_cookie_name": "connect.sid",
                "session_cookie_value": "s%3Atest",
                "from_address": "you@apache.org",
            }
        )
    )
    return path


def _wrapped(state):
    """A record shaped the way Vulnogram's read API returns it: the CVE
    document nested under a ``body`` envelope."""
    return {
        "comments": [],
        "files": [],
        "body": {
            "CNA_private": {"state": state},
            "cveMetadata": {"cveId": "CVE-2026-12345"},
        },
        "author": "x",
        "__v": 1,
    }


def test_state_only_reads_state_under_body_envelope(tmp_path, monkeypatch, capsys):
    _write_session(tmp_path / "session.json")
    monkeypatch.setenv("VULNOGRAM_SESSION", str(tmp_path / "session.json"))
    monkeypatch.setattr(record_fetch, "get_record", lambda *a, **kw: _wrapped("REVIEW"))
    rc = record_fetch.main(["--cve-id", "CVE-2026-12345", "--state-only"])
    assert rc == 0
    assert capsys.readouterr().out.strip() == "REVIEW"


def test_state_only_errors_when_cna_private_missing(tmp_path, monkeypatch, capsys):
    _write_session(tmp_path / "session.json")
    monkeypatch.setenv("VULNOGRAM_SESSION", str(tmp_path / "session.json"))
    # A record whose body carries no CNA_private object.
    monkeypatch.setattr(
        record_fetch,
        "get_record",
        lambda *a, **kw: {"body": {"cveMetadata": {"cveId": "CVE-2026-12345"}}},
    )
    rc = record_fetch.main(["--cve-id", "CVE-2026-12345", "--state-only"])
    assert rc == 7
    assert "CNA_private" in capsys.readouterr().err


def test_full_fetch_dumps_the_envelope(tmp_path, monkeypatch, capsys):
    _write_session(tmp_path / "session.json")
    monkeypatch.setenv("VULNOGRAM_SESSION", str(tmp_path / "session.json"))
    doc = _wrapped("PUBLIC")
    monkeypatch.setattr(record_fetch, "get_record", lambda *a, **kw: doc)
    rc = record_fetch.main(["--cve-id", "CVE-2026-12345"])
    assert rc == 0
    assert json.loads(capsys.readouterr().out) == doc


def test_record_body_unwraps_envelope_or_passes_through():
    wrapped = {"body": {"CNA_private": {"state": "REVIEW"}}, "comments": []}
    assert record_body(wrapped) == {"CNA_private": {"state": "REVIEW"}}
    # A locally-generated (unwrapped) document is returned unchanged.
    top_level = {"CNA_private": {"state": "PUBLIC"}, "cveMetadata": {}}
    assert record_body(top_level) is top_level
