"""
Giao tiep voi backend API.

GET  /products/pending?username=...   — lay danh sach san pham can xu ly
PATCH /products/:id/done              — danh dau san pham hoan thanh
"""
from __future__ import annotations

import json
import urllib.error
import urllib.request

from .constants import API_BASE_URL


def get_pending_products(username: str) -> list[dict]:
    """Lay danh sach san pham co status = not_start cua user."""
    url = f"{API_BASE_URL}/products/pending?username={username}"
    req = urllib.request.Request(url, headers={"Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        raise RuntimeError(f"Loi API ({e.code}): {e.reason}") from e
    except Exception as e:
        raise RuntimeError(f"Khong the ket noi API: {e}") from e


def add_sora_video(
    sora_share_link: str,
    username: str,
    backend_key: str,
    sora_mp4_share_link: str | None = None,
) -> dict:
    """Luu share link Sora vao database."""
    url = f"{API_BASE_URL}/sora-videos"
    body: dict = {
        "sora_share_link": sora_share_link,
        "username": username,
        "pipeline_status": "got_share_link",
    }
    if sora_mp4_share_link:
        body["sora_mp4_share_link"] = sora_mp4_share_link
    data = json.dumps(body).encode()
    req = urllib.request.Request(
        url,
        data=data,
        method="POST",
        headers={
            "x-backend-key": backend_key,
            "Content-Type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        if e.code == 401:
            raise RuntimeError("Backend key khong hop le (401 Unauthorized).") from e
        if e.code == 404:
            raise RuntimeError(f"User khong ton tai (404).") from e
        if e.code == 400:
            body = e.read().decode(errors="replace")
            raise RuntimeError(f"Yeu cau khong hop le (400): {body}") from e
        raise RuntimeError(f"Loi API add sora video ({e.code}): {e.reason}") from e
    except Exception as e:
        raise RuntimeError(f"Khong the ket noi API: {e}") from e


def update_mp4_by_share_link(
    sora_share_link: str,
    sora_mp4_share_link: str | None,
    backend_key: str,
) -> dict:
    """Cap nhat mp4 link cho record co share link tuong ung."""
    url = f"{API_BASE_URL}/sora-videos/update-mp4-by-share-link"
    data = json.dumps(
        {
            "sora_share_link": sora_share_link,
            "sora_mp4_share_link": sora_mp4_share_link,
        }
    ).encode()
    req = urllib.request.Request(
        url,
        data=data,
        method="PATCH",
        headers={
            "x-backend-key": backend_key,
            "Content-Type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        if e.code == 401:
            raise RuntimeError("Backend key khong hop le (401 Unauthorized).") from e
        if e.code == 400:
            body = e.read().decode(errors="replace")
            raise RuntimeError(f"Yeu cau khong hop le (400): {body}") from e
        raise RuntimeError(f"Loi API update mp4 ({e.code}): {e.reason}") from e
    except Exception as e:
        raise RuntimeError(f"Khong the ket noi API: {e}") from e


def mark_product_done(product_id: int, backend_key: str) -> dict:
    """Danh dau san pham la done sau khi xu ly xong."""
    url = f"{API_BASE_URL}/products/{product_id}/done"
    req = urllib.request.Request(
        url,
        data=b"",
        method="PATCH",
        headers={
            "x-backend-key": backend_key,
            "Content-Length": "0",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        if e.code == 401:
            raise RuntimeError("Backend key khong hop le (401 Unauthorized).") from e
        raise RuntimeError(f"Loi API mark done ({e.code}): {e.reason}") from e
    except Exception as e:
        raise RuntimeError(f"Khong the ket noi API: {e}") from e
