from fastapi.testclient import TestClient

from app.main import app


client = TestClient(app)


def preferences(**overrides):
    payload = {
        "destination": "深圳市光明区",
        "themes": ["亲子"],
        "duration": "half_day",
        "pace": "relaxed",
        "interests": ["自然风光", "生态科普"],
        "adults": 2,
        "children": 1,
        "childAges": [6],
        "transport": "public_transport",
        "budgetLevel": "standard",
        "extraRequirements": "",
    }
    payload.update(overrides)
    return payload


def test_health_reports_knowledge_and_mock_model():
    response = client.get("/api/v1/health")
    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "ok"
    assert data["knowledgeCount"] >= 15
    assert data["modelConfigured"] is True


def test_create_plan_only_returns_known_guangming_places():
    response = client.post("/api/v1/plans", json=preferences())
    assert response.status_code == 200
    data = response.json()
    assert data["conversationId"]
    assert data["itinerary"]["items"]
    assert len(data["itinerary"]["items"]) >= 2
    assert len(data["itinerary"]["items"]) <= 3
    assert all(
        item["placeId"].startswith("guangming-")
        for item in data["itinerary"]["items"]
    )
    assert len(data["itinerary"]["sources"]) == len(
        {item["placeId"] for item in data["itinerary"]["items"]}
    )


def test_indoor_requirement_filters_out_outdoor_places():
    response = client.post(
        "/api/v1/plans",
        json=preferences(
            themes=["研学"],
            interests=["文化场馆"],
            extraRequirements="下午下雨，只安排室内项目",
        ),
    )
    assert response.status_code == 200
    outdoor_ids = {
        "guangming-science-park",
        "guangming-happy-farm",
        "guangming-hongqiao-park",
        "guangming-dadingling-greenway",
    }
    ids = {item["placeId"] for item in response.json()["itinerary"]["items"]}
    assert ids.isdisjoint(outdoor_ids)


def test_adjust_existing_plan():
    created = client.post("/api/v1/plans", json=preferences()).json()
    response = client.post(
        f"/api/v1/conversations/{created['conversationId']}/messages",
        json={"message": "改成室内研学路线"},
    )
    assert response.status_code == 200
    data = response.json()
    assert data["conversationId"] == created["conversationId"]
    assert data["changeSummary"]
    assert data["itinerary"]["items"]


def test_missing_preferences_are_rejected():
    response = client.post(
        "/api/v1/plans",
        json=preferences(themes=[], interests=[]),
    )
    assert response.status_code == 422


def test_expired_or_unknown_session_is_404():
    response = client.post(
        "/api/v1/conversations/not-found/messages",
        json={"message": "慢一点"},
    )
    assert response.status_code == 404
