"""
ado_attach.py — Attach generated Playwright files to an ADO work item.

Used by the Playwright Code Generator agent to persist generated files
back to ADO as attachments on the Feature or PBI work item.
"""
from __future__ import annotations

import re
import requests

from stlc_agents.shared.auth import get_auth_headers

_API = "7.1"


def attach_file_to_work_item(
    org_url: str,
    project: str,
    work_item_id: int,
    file_name: str,
    file_content: str,
    comment: str = "Generated by QA Playwright Code Generator",
) -> dict:
    """Upload a text file and attach it to any ADO work item."""
    org_url = org_url.rstrip("/")

    safe_name = re.sub(r"[^a-zA-Z0-9._\-]", "_", file_name)

    upload = requests.post(
        f"{org_url}/{project}/_apis/wit/attachments",
        headers=get_auth_headers("application/octet-stream"),
        params={"fileName": safe_name, "api-version": _API},
        data=file_content.encode("utf-8"),
        timeout=30,
    )
    upload.raise_for_status()
    attachment_url = upload.json()["url"]

    link = requests.patch(
        f"{org_url}/{project}/_apis/wit/workitems/{work_item_id}",
        headers=get_auth_headers("application/json-patch+json"),
        params={"api-version": _API},
        json=[{
            "op": "add",
            "path": "/relations/-",
            "value": {
                "rel": "AttachedFile",
                "url": attachment_url,
                "attributes": {"comment": comment},
            },
        }],
        timeout=30,
    )
    link.raise_for_status()

    return {
        "success": True,
        "work_item_id": work_item_id,
        "file_name": safe_name,
        "attachment_url": attachment_url,
    }
