import http.client
import json
import os
from pathlib import Path
import re
import sys
from urllib.parse import urlsplit


def required(name):
    value = os.environ.get(name, "").strip()
    if not value:
        raise ValueError(f"Missing {name}")
    return value


def upload_png(filename, author, headers):
    path = Path(filename)
    if path.name != filename or path.suffix.lower() != ".png":
        raise ValueError("POST_IMAGE must name a PNG next to publish.py")
    path = Path(__file__).with_name(filename)
    with path.open("rb") as image:
        if image.read(8) != b"\x89PNG\r\n\x1a\n":
            raise ValueError("Invalid PNG signature")
        image.seek(0)
        api = http.client.HTTPSConnection("api.linkedin.com", timeout=30)
        try:
            body = json.dumps({"initializeUploadRequest": {"owner": author}})
            api.request("POST", "/rest/images?action=initializeUpload", body, headers)
            response = api.getresponse()
            print(f"Initialize image upload: HTTP {response.status}")
            if response.status != 200:
                raise ValueError("Image registration failed")
            asset = json.load(response)["value"]
        finally:
            api.close()

        url = urlsplit(asset["uploadUrl"])
        image_id = asset["image"]
        if not re.fullmatch(r"urn:li:image:[A-Za-z0-9_-]+", image_id):
            raise ValueError("Invalid image ID")
        if url.scheme != "https" or not (url.hostname or "").endswith((".linkedin.com", ".licdn.com")):
            raise ValueError("Invalid image upload destination")
        upload = http.client.HTTPSConnection(url.hostname, timeout=60)
        try:
            upload_headers = {
                "Authorization": headers["Authorization"],
                "Content-Type": "image/png",
                "Content-Length": str(os.fstat(image.fileno()).st_size),
            }
            target = url.path + ("?" + url.query if url.query else "")
            upload.request("PUT", target, image, upload_headers)
            response = upload.getresponse()
            print(f"Upload image: HTTP {response.status}")
            if not 200 <= response.status < 300:
                raise ValueError("Image upload failed")
        finally:
            upload.close()
    return image_id


def main():
    try:
        token = required("LINKEDIN_ACCESS_TOKEN")
        author = required("LINKEDIN_PERSON_URN")
        version = required("LINKEDIN_API_VERSION")
        if not re.fullmatch(r"[!-~]+", token):
            raise ValueError("Invalid LINKEDIN_ACCESS_TOKEN")
        if not re.fullmatch(r"urn:li:person:[A-Za-z0-9_-]+", author):
            raise ValueError("Invalid LINKEDIN_PERSON_URN")
        if not re.fullmatch(r"[0-9]{4}(0[1-9]|1[0-2])", version):
            raise ValueError("LINKEDIN_API_VERSION must be YYYYMM")
    except ValueError as error:
        print(error, file=sys.stderr)
        return 1

    image_name = os.environ.get("POST_IMAGE", "")
    text = ""
    if not image_name:
        try:
            text = Path(__file__).with_name("post.txt").read_text(encoding="utf-8-sig")
        except (OSError, UnicodeError):
            print("Cannot read post.txt as UTF-8.", file=sys.stderr)
            return 1
        if not text.strip():
            print("post.txt is empty.", file=sys.stderr)
            return 1

    # Escape LinkedIn's reserved commentary characters so post.txt is plain text.
    escapes = str.maketrans({c: "\\" + c for c in "\\|{}@[]()<>#*_~"})
    payload = {
        "author": author,
        "commentary": text.removesuffix("\n").translate(escapes),
        "visibility": "PUBLIC",
        "distribution": {
            "feedDistribution": "MAIN_FEED",
            "targetEntities": [],
            "thirdPartyDistributionChannels": [],
        },
        "lifecycleState": "PUBLISHED",
    }
    headers = {
        "Authorization": f"Bearer {token}",
        "Linkedin-Version": version,
        "X-Restli-Protocol-Version": "2.0.0",
        "Content-Type": "application/json",
    }
    if image_name:
        try:
            image_id = upload_png(image_name, author, headers)
        except (OSError, http.client.HTTPException, ValueError, KeyError, TypeError):
            print("Could not prepare the image. No post was submitted.", file=sys.stderr)
            return 1
        payload["content"] = {"media": {"id": image_id}}

    connection = http.client.HTTPSConnection("api.linkedin.com", timeout=30)
    try:
        body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
        connection.request("POST", "/rest/posts", body=body, headers=headers)
        response = connection.getresponse()
        post_id = response.getheader("x-restli-id", "")
        if not re.fullmatch(r"urn:li:(?:share|ugcPost):[0-9]+", post_id):
            post_id = "(unavailable)"
        print(f"HTTP {response.status} | x-restli-id: {post_id}")
        return 0 if response.status == 201 else 1
    except (OSError, http.client.HTTPException):
        print("No HTTP response. Check the profile before retrying.", file=sys.stderr)
        return 1
    finally:
        connection.close()


if __name__ == "__main__":
    sys.exit(main())
