"""Tests for the BSS script generator."""
from __future__ import annotations

import json

import pytest

from bvd.engine.generator import _parse_response

# ── _parse_response ───────────────────────────────────────────────────────────

def test_parse_valid_response():
    payload = {
        "skill_json": {
            "id": "csv-summarizer",
            "name": "CSV Summarizer",
            "description": "Extracts stats from CSV prompts",
            "tags": ["csv", "data"],
            "version": "1.0.0",
            "author": "bibividi-generator",
        },
        "skill_py": "print(PROMPT[:100])",
    }
    skill_json, skill_py = _parse_response(json.dumps(payload))
    assert skill_json["id"] == "csv-summarizer"
    assert skill_py == "print(PROMPT[:100])"


def test_parse_strips_markdown_fences():
    payload = {
        "skill_json": {"id": "my-skill", "name": "X", "description": "Y", "tags": []},
        "skill_py": "print(PROMPT)",
    }
    raw = f"```json\n{json.dumps(payload)}\n```"
    skill_json, skill_py = _parse_response(raw)
    assert skill_json is not None
    assert skill_json["id"] == "my-skill"


def test_parse_invalid_id_gets_replaced():
    payload = {
        "skill_json": {"id": "INVALID ID!", "name": "X", "description": "Y", "tags": []},
        "skill_py": "print(PROMPT)",
    }
    skill_json, _ = _parse_response(json.dumps(payload))
    assert skill_json is not None
    assert skill_json["id"].startswith("generated-")


def test_parse_missing_id_gets_generated():
    payload = {
        "skill_json": {"name": "X", "description": "Y", "tags": []},
        "skill_py": "print(PROMPT)",
    }
    skill_json, _ = _parse_response(json.dumps(payload))
    assert skill_json is not None
    assert skill_json["id"].startswith("generated-")


def test_parse_invalid_json_returns_none():
    skill_json, skill_py = _parse_response("not json at all")
    assert skill_json is None
    assert skill_py is None


def test_parse_missing_skill_py_returns_none():
    payload = {"skill_json": {"id": "x", "name": "X", "description": "Y", "tags": []}}
    skill_json, skill_py = _parse_response(json.dumps(payload))
    assert skill_json is None
    assert skill_py is None


# ── Generator.generate (no API key) ──────────────────────────────────────────

@pytest.mark.asyncio
async def test_generate_skips_without_api_key(monkeypatch):
    """Generator should return None immediately when no API key is configured."""
    from bvd.engine.generator import Generator

    monkeypatch.setattr("bvd.engine.generator.settings.generator_enabled", True)
    monkeypatch.setattr("bvd.engine.generator.settings.generator_api_key", None)

    gen = Generator()
    result = await gen.generate("Analyse ce contrat et résume les clauses.")
    assert result is None


@pytest.mark.asyncio
async def test_generate_skips_when_disabled(monkeypatch):
    monkeypatch.setattr("bvd.engine.generator.settings.generator_enabled", False)
    monkeypatch.setattr("bvd.engine.generator.settings.generator_api_key", "fake-key")

    from bvd.engine.generator import Generator
    gen = Generator()
    result = await gen.generate("any prompt")
    assert result is None
