import hashlib
import hmac
import httpx


def verify_webhook(secret: str, payload_bytes: bytes, signature_header: str) -> bool:
    expected = hmac.new(secret.encode(), payload_bytes, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature_header)


def parse_issue(payload: dict) -> tuple[str, str, str, str | None]:
    """Returns (issue_id, title, description, repo_url)."""
    data = payload.get("data", {})
    issue_id = data.get("id", "")
    title = data.get("title", "")
    description = data.get("description", "") or ""

    repo_url: str | None = None
    attachments = data.get("attachments", {}).get("nodes", [])
    for att in attachments:
        url = att.get("url", "")
        if "gitlab" in url or "github" in url or ".git" in url:
            repo_url = url
            break

    return issue_id, title, description, repo_url


async def post_comment(api_key: str, issue_id: str, text: str) -> None:
    mutation = """
    mutation CommentCreate($issueId: String!, $body: String!) {
        commentCreate(input: { issueId: $issueId, body: $body }) {
            success
        }
    }
    """
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            "https://api.linear.app/graphql",
            json={"query": mutation, "variables": {"issueId": issue_id, "body": text}},
            headers={"Authorization": api_key, "Content-Type": "application/json"},
        )
        resp.raise_for_status()
