"""Redaction for execution output that is safe to send to browser clients."""
from __future__ import annotations

import re


_URL_RE = re.compile(r"https?://[^\s<>\]\[)]+", re.IGNORECASE)
_LOCAL_PATH_RE = re.compile(
    r"(?:[A-Za-z]:[\\/]|/)(?:[^\s\\/]+[\\/])+[^\s]*"
)
_GENERATED_PROJECT_ROOT_RE = re.compile(r"(?i)p2hs-[0-9a-f]{32}[\\/]")
_INTERNAL_FILE_RE = re.compile(
    r"(?i)(?:saved deploy artifact|deploy artifact)\s+[^\r\n]+"
)
_INTERNAL_LABEL_RE = re.compile(r"(?i)\[p2hs-codegen\]|github actions|p2hs ai")


def redact_public_output(value: str | None) -> str | None:
    """Remove URLs and runner-local paths from text delivered to project clients.

    Provider URLs, managed repository URLs, authenticated clone URLs, and runner
    filesystem paths are implementation details. The browser receives the
    platform's canonical preview/deployment URL through the normal project API.
    """
    if value is None:
        return None
    text = str(value)
    text = _URL_RE.sub("[internal URL redacted]", text)
    text = _INTERNAL_FILE_RE.sub("deployment artifact saved", text)
    text = _LOCAL_PATH_RE.sub("[internal path redacted]", text)
    # Keep useful relative edit paths while removing the generated project
    # directory that identifies the managed workspace.
    text = _GENERATED_PROJECT_ROOT_RE.sub("", text)
    text = _INTERNAL_LABEL_RE.sub(
        lambda match: {
            "[p2hs-codegen]": "",
            "github actions": "the build service",
            "p2hs ai": "the build service",
        }[match.group(0).lower()],
        text,
    )
    return text
