from __future__ import annotations

"""SDK briefs resource tests — mocked HTTP."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from nexure import DecisionBrief, Nexure
from pytest_httpx import HTTPXMock

MOCK_BRIEF = {
    "id": "brf_abc123def456",
    "package_id": None,
    "template_id": "credit_underwriting",
    "template_version": "1.0.0",
    "synthesis": "Strong applicant with FICO 711.",
    "key_metrics_assessment": "DTI at 0.38 slightly above guideline.",
    "risk_narrative": "Moderate DTI is the primary concern.",
    "flags": [
        {"id": "high_dti", "name": "Elevated DTI", "severity": "medium", "message": "DTI above 36%"}
    ],
    "comparables": None,
    "pattern_match": "approve",
    "quality_score": 72,
    "quality_level": "strong",
    "quality_components": {"evidence_completeness": 100, "comparables_depth": 0, "flag_coverage": 100, "data_recency": 0},
    "quality_summary": "Based on complete evidence, no comparable decisions yet.",
    "model_used": "claude-sonnet-4-5-20250929",
    "generation_time_ms": 3200,
    "tenant_id": "tenant_dev",
    "created_at": "2025-01-15T10:30:00Z",
}


class TestBriefsGenerate:
    def test_generate_inline(self, httpx_mock: HTTPXMock) -> None:
        httpx_mock.add_response(
            method="POST",
            url="http://test:8000/v1/briefs/generate",
            json=MOCK_BRIEF,
            status_code=201,
        )

        nx = Nexure(api_key="test_key", base_url="http://test:8000/v1")
        result = nx.briefs.generate(
            decision_type="credit_underwriting",
            evidence={
                "fico_score": 711,
                "dti_ratio": 0.38,
                "loan_amount": 45000,
                "loan_purpose": "purchase",
                "annual_income": 127000,
            },
        )
        nx.close()

        assert isinstance(result, DecisionBrief)
        assert result.id == "brf_abc123def456"
        assert result.template_id == "credit_underwriting"
        assert result.quality_score == 72
        assert result.quality_level == "strong"
        assert len(result.flags) == 1
        assert result.flags[0]["id"] == "high_dti"

    def test_generate_with_package_id(self, httpx_mock: HTTPXMock) -> None:
        httpx_mock.add_response(
            method="POST",
            url="http://test:8000/v1/briefs/generate",
            json={**MOCK_BRIEF, "package_id": "pkg_test123456"},
            status_code=201,
        )

        nx = Nexure(api_key="test_key", base_url="http://test:8000/v1")
        result = nx.briefs.generate(package_id="pkg_test123456")
        nx.close()

        assert isinstance(result, DecisionBrief)
        assert result.package_id == "pkg_test123456"

    def test_degraded_brief_fields(self, httpx_mock: HTTPXMock) -> None:
        degraded = {
            "id": "brf_degraded123",
            "package_id": None,
            "template_id": "credit_underwriting",
            "template_version": "1.0.0",
            "synthesis": "",
            "key_metrics_assessment": "",
            "risk_narrative": "",
            "flags": [],
            "comparables": None,
            "pattern_match": None,
            "quality_score": 50,
            "quality_level": "moderate",
            "quality_components": {},
            "quality_summary": "",
            "model_used": None,
            "generation_time_ms": 5,
            "tenant_id": "tenant_dev",
            "created_at": "2025-01-15T10:30:00Z",
        }
        httpx_mock.add_response(
            method="POST",
            url="http://test:8000/v1/briefs/generate",
            json=degraded,
            status_code=201,
        )

        nx = Nexure(api_key="test_key", base_url="http://test:8000/v1")
        result = nx.briefs.generate(
            decision_type="credit_underwriting",
            evidence={
                "fico_score": 711,
                "dti_ratio": 0.38,
                "loan_amount": 45000,
                "loan_purpose": "purchase",
                "annual_income": 127000,
            },
        )
        nx.close()

        assert result.quality_score == 50
        assert result.quality_level == "moderate"
        assert result.model_used is None
        assert result.synthesis == ""

    def test_brief_with_comparables(self, httpx_mock: HTTPXMock) -> None:
        brief_with_comp = {
            **MOCK_BRIEF,
            "comparables": {"similar_count": 12, "approve_rate": 0.75},
        }
        httpx_mock.add_response(
            method="POST",
            url="http://test:8000/v1/briefs/generate",
            json=brief_with_comp,
            status_code=201,
        )

        nx = Nexure(api_key="test_key", base_url="http://test:8000/v1")
        result = nx.briefs.generate(
            decision_type="credit_underwriting",
            evidence={
                "fico_score": 711,
                "dti_ratio": 0.38,
                "loan_amount": 45000,
                "loan_purpose": "purchase",
                "annual_income": 127000,
            },
            include_comparables=True,
        )
        nx.close()

        assert result.comparables is not None
        assert result.comparables["similar_count"] == 12
