def owner_payload():
    return {
        "email": "owner@example.com",
        "password": "correct horse battery staple",
        "display_name": "Owner",
        "workspace_name": "Personal",
        "timezone": "Asia/Dubai",
    }


def csrf_headers(client):
    return {"x-csrf-token": client.cookies.get("hayva_csrf")}


def profile_payload():
    return {
        "profile_key": "primary-planner",
        "display_name": "Primary Planner",
        "provider": "openai",
        "model_id": "owner-selected-model",
        "enabled": True,
        "capabilities": ["planning", "text"],
    }


def test_model_profiles_are_honest_scoped_and_protected_when_assigned(auth_client):
    auth_client.post("/api/v1/setup/owner", json=owner_payload())
    empty = auth_client.get("/api/v1/model-profiles")
    assert empty.status_code == 200
    assert empty.json()["profiles"] == []
    assert empty.json()["provider_state"] == "unconfigured"

    missing_csrf = auth_client.post("/api/v1/model-profiles", json=profile_payload())
    assert missing_csrf.status_code == 403
    created = auth_client.post(
        "/api/v1/model-profiles", json=profile_payload(), headers=csrf_headers(auth_client)
    )
    assert created.status_code == 201
    profile = created.json()["profile"]
    assert profile["provider_state"] == "unconfigured"
    assert profile["model_id"] == "owner-selected-model"

    default_agent = auth_client.get("/api/v1/agents").json()["agents"][0]
    assigned = auth_client.patch(
        f"/api/v1/agents/{default_agent['id']}",
        json={"preferred_model": "primary-planner"},
        headers=csrf_headers(auth_client),
    )
    assert assigned.status_code == 200
    assert assigned.json()["agent"]["preferred_model"] == "primary-planner"

    referenced = auth_client.delete(
        f"/api/v1/model-profiles/{profile['id']}", headers=csrf_headers(auth_client)
    )
    assert referenced.status_code == 409
    assert referenced.json()["error"]["code"] == "MODEL_PROFILE_REFERENCED"


def test_agent_rejects_unknown_or_disabled_model_profile(auth_client):
    auth_client.post("/api/v1/setup/owner", json=owner_payload())
    default_agent = auth_client.get("/api/v1/agents").json()["agents"][0]
    unknown = auth_client.patch(
        f"/api/v1/agents/{default_agent['id']}",
        json={"preferred_model": "missing-profile"},
        headers=csrf_headers(auth_client),
    )
    assert unknown.status_code == 422
    assert unknown.json()["error"]["code"] == "AGENT_MODEL_PROFILE_INVALID"

    payload = profile_payload()
    payload["enabled"] = False
    auth_client.post(
        "/api/v1/model-profiles", json=payload, headers=csrf_headers(auth_client)
    )
    disabled = auth_client.patch(
        f"/api/v1/agents/{default_agent['id']}",
        json={"preferred_model": "primary-planner"},
        headers=csrf_headers(auth_client),
    )
    assert disabled.status_code == 422
