"""VenomQA v1 actions for the mock GitHub API.

Each function follows the (api, context) signature so the framework
auto-injects both the HTTP client and the shared context store.

Context keys written by these actions:
    user_login   — login of the most recently created user
    repo_id      — id of the most recently created repo
    issue_num    — issue number of the most recently created issue
    open_issues  — list of issues from the last list_open_issues call
"""

from __future__ import annotations

import uuid

from venomqa.v1.core.action import ActionResult


def create_user(api, context) -> ActionResult:  # type: ignore[no-untyped-def]
    """POST /users — create a new user, store login in context."""
    login = f"user-{uuid.uuid4().hex[:8]}"
    result = api.post(
        "/users",
        json={"login": login, "email": f"{login}@qa.test"},
    )
    if result.success and result.response.status_code == 201:
        context.set("user_login", login)
        context.set("user_id", result.response.body.get("id"))
    return result


def create_repo(api, context) -> ActionResult:  # type: ignore[no-untyped-def]
    """POST /repos — create a repo owned by the current user."""
    owner = context.get("user_login", "")
    repo_name = f"repo-{uuid.uuid4().hex[:6]}"
    result = api.post(
        "/repos",
        json={"owner_login": owner, "name": repo_name},
    )
    if result.success and result.response.status_code == 201:
        context.set("repo_id", result.response.body.get("id"))
        context.set("repo_name", repo_name)
    return result


def list_repos(api, context) -> ActionResult:  # type: ignore[no-untyped-def]
    """GET /repos — list all repos for the current user."""
    owner = context.get("user_login", "")
    return api.get("/repos", params={"owner": owner} if owner else None)


def create_issue(api, context) -> ActionResult:  # type: ignore[no-untyped-def]
    """POST /repos/{repo_id}/issues — open a new issue."""
    repo_id = context.get("repo_id", "")
    result = api.post(
        f"/repos/{repo_id}/issues",
        json={"title": f"Test issue {uuid.uuid4().hex[:4]}", "body": "Auto-generated by VenomQA."},
    )
    if result.success and result.response.status_code == 201:
        context.set("issue_num", result.response.body.get("number"))
    return result


def list_open_issues(api, context) -> ActionResult:  # type: ignore[no-untyped-def]
    """GET /repos/{repo_id}/issues?state=open — list open issues.

    Stores the response body in context["open_issues"] so the invariant
    can inspect it without making an additional HTTP call.
    """
    repo_id = context.get("repo_id", "")
    result = api.get(f"/repos/{repo_id}/issues", params={"state": "open"})
    if result.success:
        context.set("open_issues", result.response.body or [])
    return result


def close_issue(api, context) -> ActionResult:  # type: ignore[no-untyped-def]
    """PATCH /repos/{repo_id}/issues/{num} — close the most recently created issue."""
    repo_id = context.get("repo_id", "")
    num = context.get("issue_num", 0)
    return api.patch(
        f"/repos/{repo_id}/issues/{num}",
        json={"state": "closed"},
    )


def delete_repo(api, context) -> ActionResult:  # type: ignore[no-untyped-def]
    """DELETE /repos/{repo_id} — delete the current repo."""
    repo_id = context.get("repo_id", "")
    result = api.delete(f"/repos/{repo_id}")
    if result.success:
        # Verify deletion is effective (GET should return 404)
        verify = api.get(f"/repos/{repo_id}")
        context.set("deleted_repo_id", repo_id)
        context.set("deleted_repo_status", verify.response.status_code if verify.response else None)
        # Clear context so subsequent actions don't use the deleted repo
        context.set("repo_id", "")
    return result
