# qa-copilot/mobile_recorder.py
"""
Mobile test recorder helper (#19).

Accepts captured mobile interactions (tap, input, swipe, assert)
and generates Appium test code via LLM. Works with both Android and iOS.
"""
from __future__ import annotations

from llm_providers import llm_json


def actions_to_story(actions: list[dict], app_name: str = "") -> str:
    lines = [f"Mobile app: {app_name or 'Unknown'}", "", "Recorded user actions:"]
    for i, action in enumerate(actions, 1):
        desc = action.get("description", action.get("type", "action"))
        locator = action.get("locator", "")
        value = action.get("value", "")
        parts = [f"{i}. {desc}"]
        if locator:
            parts.append(f"(element: {locator})")
        if value:
            parts.append(f'[input: "{value}"]')
        lines.append(" ".join(parts))
    if not actions:
        lines.append("(no actions recorded)")
    return "\n".join(lines)


_MOBILE_TEST_SCHEMA = {
    "type": "object",
    "properties": {
        "tests": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "title": {"type": "string"},
                    "steps": {"type": "array", "items": {"type": "string"}},
                    "code": {"type": "string"},
                },
                "required": ["title", "steps"],
            },
        }
    },
    "required": ["tests"],
}


def generate_from_actions(
    actions: list[dict],
    app_name: str = "",
    platform: str = "android",
    provider: str = "ollama",
    model: str = "",
    framework: str = "appium",
) -> dict:
    story = actions_to_story(actions, app_name=app_name)
    system = (
        f"You are a mobile QA engineer. Generate {framework} tests for {platform}. "
        f"The user recorded interactions in a mobile app. Convert them into structured test cases "
        f"with step descriptions and executable {framework} code (Java/Kotlin). "
        f"Return JSON with a 'tests' array."
    )
    try:
        result = llm_json(
            system_prompt=system,
            user_prompt=story,
            provider=provider,
            model=model,
            temperature=0.2,
            schema=_MOBILE_TEST_SCHEMA,
        )
        if isinstance(result, dict) and "tests" in result:
            return result
        return {"tests": []}
    except Exception as e:
        print(f"  ⚠  Mobile test generation failed: {e}")
        return {"tests": []}
