from fastapi.testclient import TestClient
from app.main import app
from app.services import cloud

client = TestClient(app)

orig_enabled = cloud.enabled
orig_action = cloud.action
orig_start = cloud.start_rp_action
orig_image = cloud.image_action
calls = {"start": [], "image": [], "action": []}

scenario = {
    "id": "scenario-cloud-1",
    "item_type": "scenario",
    "title": "Cloud Scenario",
    "summary": "Structured scenario",
    "version": 7,
    "canon_mode": "Strict Canon",
    "parent_character": "Xaden",
    "payload": {
        "scenario_schema": "melumiyachat_scenario_dossier_v3",
        "world_bible_seed": {
            "schema_version": 4,
            "overview": {"name": "Cloud Scenario", "description": "Structured scenario"},
            "characters": [], "history_backstory": [], "background_facts": [],
            "relationship_history": [], "core_canon": [], "locations": [],
            "secrets_knowledge": [], "groups_factions": [], "important_objects": [],
            "world_rules": [], "current_state": [], "physical_continuity": [],
            "story_timeline": [], "custom_entries": [], "auto_review_conflicts": []
        }
    }
}

try:
    cloud.enabled = lambda: True

    def fake_action(token, action_name, **payload):
        calls["action"].append((action_name, payload))
        if action_name == "me":
            return {"user": {"id": "u1", "email": "test@example.com"}, "profile": {"display_name": "Tester"}, "entitlement": {"plan_tier": "Free"}, "role": "User"}
        if action_name == "list_public_content":
            return [scenario]
        raise AssertionError(f"Unexpected cloud.action call: {action_name}")

    def fake_start(token, **payload):
        calls["start"].append(payload)
        return {"ok": True, "conversation_id": "rp-cloud-1", "conversation": {"id": "rp-cloud-1"}, "scenario_template_copied": True}

    def fake_image(token, action_name="generate", **payload):
        calls["image"].append((action_name, payload))
        return {"url": "https://example.test/generated.png", "mode": "provider", "plain": "Image generated."}

    cloud.action = fake_action
    cloud.start_rp_action = fake_start
    cloud.image_action = fake_image

    headers = {"Authorization": "Bearer regression-token"}

    r = client.post(
        "/api/discover/scenarios/scenario-cloud-1/start",
        headers=headers,
        json={
            "title": "My RP", "persona_id": "persona-123", "persona_name": "Mara",
            "start_date": "2026-08-19", "start_time": "16:00"
        },
    )
    assert r.status_code == 200, r.text
    assert r.json()["conversation_id"] == "rp-cloud-1"
    assert calls["start"], "Windows did not use canonical melumiyachat-start-rp path"
    sp = calls["start"][0]
    assert sp["scenario_id"] == "scenario-cloud-1"
    assert sp["persona_id"] == "persona-123"
    assert sp["start_date"] == "2026-08-19" and sp["start_time"] == "16:00"
    assert not any(name == "create_rp" for name, _ in calls["action"]), "Windows fell back to generic create_rp for a cloud Scenario"

    r = client.post(
        "/api/images/generate",
        headers=headers,
        json={"prompt": "Portrait of Mara", "style": "Realistic", "aspect": "1:1", "target": "persona"},
    )
    assert r.status_code == 200, r.text
    assert r.json()["mode"] == "provider"
    assert calls["image"] and calls["image"][0][0] == "generate", "Windows image generator did not use cloud image service"
    assert calls["image"][0][1]["target"] == "persona"

    print("PASS platform connection regression")
finally:
    cloud.enabled = orig_enabled
    cloud.action = orig_action
    cloud.start_rp_action = orig_start
    cloud.image_action = orig_image
