"""YouSoft Dış API - Tek Dosya Python İstemcisi (sıfır harici paket)

Uyumluluk: Python 3.9+ (yalnızca standart kütüphane, pip install gerekmez)
Dokümantasyon: https://developers.yousoft.com.tr/istemciler

Hızlı kullanım:
    from yousoft_client import YouSoftClient

    client = YouSoftClient("ysk_...", "guvenlik_anahtariniz")  # varsayılan Test API (XML)
    # JSON için: YouSoftClient("ysk_...", "secret", format="json")
    # Canlı için: YouSoftClient("ysk_...", "secret", taban=YouSoftClient.CANLI_TABAN)

    mukellef = client.mukellef_sorgula("1234567890")
    print(mukellef.status, mukellef.text)

    fatura = client.fatura_kes(xml_govde)
    pdf = client.pdf_indir(fatura_id)
    with open("fatura.pdf", "wb") as f:
        f.write(pdf.content)
"""

from __future__ import annotations

import hashlib
import hmac
import json
import re
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from dataclasses import dataclass, field
from typing import Dict, Iterator, Optional


@dataclass(frozen=True)
class YouSoftYanit:
    status: int
    content: bytes
    content_type: str
    request_id: str
    headers: Dict[str, str] = field(default_factory=dict)

    @property
    def ok(self) -> bool:
        return 200 <= self.status < 300

    @property
    def text(self) -> str:
        return self.content.decode("utf-8", errors="replace")

    @property
    def rate_limit_remaining(self) -> str:
        return self.headers.get("x-ratelimit-remaining", "")

    @property
    def rate_limit_reset(self) -> str:
        return self.headers.get("x-ratelimit-reset", "")

    @property
    def rate_limit_resource(self) -> str:
        return self.headers.get("x-ratelimit-resource", "")

    @property
    def content_disposition(self) -> str:
        return self.headers.get("content-disposition", "")


class YouSoftClient:
    TEST_TABAN = "https://test-api.yousoft.com.tr"
    CANLI_TABAN = "https://api.yousoft.com.tr"

    def __init__(
        self,
        api_key: str,
        api_secret: str,
        taban: str = TEST_TABAN,
        format: str = "xml",
        timeout: int = 60,
    ) -> None:
        if not api_key or not api_key.strip() or not api_secret or not api_secret.strip():
            raise ValueError("api_key ve api_secret zorunludur.")
        self.api_key = api_key.strip()
        self._secret = api_secret.strip().encode("utf-8")
        self.taban = taban.rstrip("/")
        self.format = "json" if format.lower() == "json" else "xml"
        self.timeout = timeout

    def kimlik(self, firma_dahil: bool = False) -> YouSoftYanit:
        return self.istek("GET", "/v1/me?include=firma" if firma_dahil else "/v1/me")

    def mukellef_sorgula(self, vkn_tckn: str) -> YouSoftYanit:
        """Alıcının GİB e-Fatura/e-İrsaliye mükellefiyetini ve PK etiketlerini sorgular (ücretsiz)."""
        return self.istek("GET", f"/v1/e-invoice-inboxes/{self._yol_parcasi(vkn_tckn)}")

    def serileri_listele(self, belge_tipi: str = "") -> YouSoftYanit:
        """Firmanın aktif fatura/belge serilerini listeler (çok şubeli kullanımda series ön eki için)."""
        tip = belge_tipi.strip()
        yol = f"/v1/series?filter[document_type][eq]={urllib.parse.quote(tip, safe='')}" if tip else "/v1/series"
        return self.istek("GET", yol)

    def fatura_kes(self, govde: str, idempotency_key: Optional[str] = None) -> YouSoftYanit:
        """Fatura oluşturur. Idempotency-Key yalnızca send:true gönderiminde otomatik üretilir."""
        anahtar = idempotency_key
        if anahtar is None and self._gonderim_mi(govde, self.format):
            anahtar = str(uuid.uuid4())
        return self.istek("POST", "/v1/invoices", govde, anahtar)

    def fatura_guncelle(self, fatura_id: str, govde: str) -> YouSoftYanit:
        """Taslak faturayı günceller (PATCH /v1/invoices/{id})."""
        return self.istek("PATCH", f"/v1/invoices/{self._yol_parcasi(fatura_id)}", govde)

    def fatura_gonder(
        self, fatura_id: str, govde: str = "", idempotency_key: Optional[str] = None
    ) -> YouSoftYanit:
        """Taslak faturayı gönderim kuyruğuna alır (202 Accepted)."""
        return self.istek(
            "POST",
            f"/v1/invoices/{self._yol_parcasi(fatura_id)}/send",
            govde,
            idempotency_key or str(uuid.uuid4()),
        )

    def fatura_oku(
        self, fatura_id: str, cari_dahil: bool = False, kalemler_dahil: bool = False
    ) -> YouSoftYanit:
        inc = []
        if cari_dahil:
            inc.append("contact")
        if kalemler_dahil:
            inc.append("items")
        fid = self._yol_parcasi(fatura_id)
        yol = f"/v1/invoices/{fid}?include={','.join(inc)}" if inc else f"/v1/invoices/{fid}"
        return self.istek("GET", yol)

    def faturalari_listele(self, sorgu: str = "") -> YouSoftYanit:
        return self.istek("GET", self._liste_yolu("/v1/invoices", sorgu))

    def pdf_indir(self, fatura_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/invoices/{self._yol_parcasi(fatura_id)}/pdf")

    def xml_indir(self, fatura_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/invoices/{self._yol_parcasi(fatura_id)}/xml")

    def html_indir(self, fatura_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/invoices/{self._yol_parcasi(fatura_id)}/html")

    def fatura_iptal(self, fatura_id: str, govde: str) -> YouSoftYanit:
        return self.istek("POST", f"/v1/invoices/{self._yol_parcasi(fatura_id)}/cancel", govde)

    def fatura_iptal_geri_al(self, fatura_id: str) -> YouSoftYanit:
        """İptal edilmiş ve GİB'e henüz raporlanmamış e-Arşiv faturasının iptalini geri alır."""
        return self.istek("POST", f"/v1/invoices/{self._yol_parcasi(fatura_id)}/cancel/withdraw")

    def gelen_faturalari_listele(self, sorgu: str = "") -> YouSoftYanit:
        return self.istek("GET", self._liste_yolu("/v1/inbox-invoices", sorgu))

    def gelen_fatura_oku(self, fatura_id: str, kalemler_dahil: bool = False) -> YouSoftYanit:
        fid = self._yol_parcasi(fatura_id)
        yol = f"/v1/inbox-invoices/{fid}?include=items" if kalemler_dahil else f"/v1/inbox-invoices/{fid}"
        return self.istek("GET", yol)

    def gelen_fatura_kabul(self, fatura_id: str, govde: str = "") -> YouSoftYanit:
        return self.istek("POST", f"/v1/inbox-invoices/{self._yol_parcasi(fatura_id)}/accept", govde)

    def gelen_fatura_red(self, fatura_id: str, govde: str) -> YouSoftYanit:
        return self.istek("POST", f"/v1/inbox-invoices/{self._yol_parcasi(fatura_id)}/reject", govde)

    def gelen_pdf_indir(self, fatura_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/inbox-invoices/{self._yol_parcasi(fatura_id)}/pdf")

    def gelen_xml_indir(self, fatura_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/inbox-invoices/{self._yol_parcasi(fatura_id)}/xml")

    def gelen_html_indir(self, fatura_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/inbox-invoices/{self._yol_parcasi(fatura_id)}/html")

    def makbuzlari_listele(self, sorgu: str = "") -> YouSoftYanit:
        return self.istek("GET", self._liste_yolu("/v1/receipts", sorgu))

    def makbuz_kes(self, govde: str, idempotency_key: Optional[str] = None) -> YouSoftYanit:
        """e-SMM veya e-Müstahsil makbuzu oluşturur ve senkron gönderir."""
        return self.istek("POST", "/v1/receipts", govde, idempotency_key or str(uuid.uuid4()))

    def esmm_kes(self, govde: str, idempotency_key: Optional[str] = None) -> YouSoftYanit:
        return self.makbuz_kes(govde, idempotency_key)

    def makbuz_oku(self, makbuz_id: str, kalemler_dahil: bool = False) -> YouSoftYanit:
        mid = self._yol_parcasi(makbuz_id)
        yol = f"/v1/receipts/{mid}?include=items" if kalemler_dahil else f"/v1/receipts/{mid}"
        return self.istek("GET", yol)

    def makbuz_iptal(self, makbuz_id: str, govde: str = "") -> YouSoftYanit:
        return self.istek("POST", f"/v1/receipts/{self._yol_parcasi(makbuz_id)}/cancel", govde)

    def makbuz_iptal_geri_al(self, makbuz_id: str) -> YouSoftYanit:
        return self.istek("POST", f"/v1/receipts/{self._yol_parcasi(makbuz_id)}/cancel/withdraw")

    def makbuz_xml_indir(self, makbuz_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/receipts/{self._yol_parcasi(makbuz_id)}/xml")

    def makbuz_pdf_indir(self, makbuz_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/receipts/{self._yol_parcasi(makbuz_id)}/pdf")

    def makbuz_html_indir(self, makbuz_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/receipts/{self._yol_parcasi(makbuz_id)}/html")

    def esmm_pdf_indir(self, makbuz_id: str) -> YouSoftYanit:
        return self.makbuz_pdf_indir(makbuz_id)

    def irsaliyeleri_listele(self, sorgu: str = "") -> YouSoftYanit:
        return self.istek("GET", self._liste_yolu("/v1/despatches", sorgu))

    def irsaliye_kes(self, govde: str, idempotency_key: Optional[str] = None) -> YouSoftYanit:
        """e-İrsaliye oluşturur ve senkron gönderir."""
        return self.istek("POST", "/v1/despatches", govde, idempotency_key or str(uuid.uuid4()))

    def irsaliye_oku(self, irsaliye_id: str, kalemler_dahil: bool = False) -> YouSoftYanit:
        iid = self._yol_parcasi(irsaliye_id)
        yol = f"/v1/despatches/{iid}?include=items" if kalemler_dahil else f"/v1/despatches/{iid}"
        return self.istek("GET", yol)

    def irsaliye_xml_indir(self, irsaliye_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/despatches/{self._yol_parcasi(irsaliye_id)}/xml")

    def irsaliye_pdf_indir(self, irsaliye_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/despatches/{self._yol_parcasi(irsaliye_id)}/pdf")

    def irsaliye_html_indir(self, irsaliye_id: str) -> YouSoftYanit:
        return self.istek("GET", f"/v1/despatches/{self._yol_parcasi(irsaliye_id)}/html")

    def irsaliye_kabul(self, irsaliye_id: str, govde: str = "") -> YouSoftYanit:
        return self.istek("POST", f"/v1/despatches/{self._yol_parcasi(irsaliye_id)}/accept", govde)

    def irsaliye_red(self, irsaliye_id: str, govde: str) -> YouSoftYanit:
        return self.istek("POST", f"/v1/despatches/{self._yol_parcasi(irsaliye_id)}/reject", govde)

    def tum_sayfalari_gez(self, taban_yol: str, sorgu: str = "") -> Iterator[YouSoftYanit]:
        """Keyset sayfalanan bir /v1/* listesini meta.next_cursor bitene kadar gezer."""
        if "?" in taban_yol:
            saf_yol, gomulu = taban_yol.split("?", 1)
        else:
            saf_yol, gomulu = taban_yol, ""
        temiz_sorgu = "&".join(
            p for p in (self._cursor_temizle(gomulu), self._cursor_temizle(sorgu)) if p
        )
        cursor = ""
        gorulen: set = set()
        while True:
            parcalar = []
            if temiz_sorgu:
                parcalar.append(temiz_sorgu)
            if cursor:
                parcalar.append(f"cursor={urllib.parse.quote(cursor, safe='')}")
            yol = f"{saf_yol}?{'&'.join(parcalar)}" if parcalar else saf_yol
            yanit = self.istek("GET", yol)
            yield yanit
            if not yanit.ok:
                return
            sonraki = self._sonraki_cursor_oku(yanit.text, yanit.content_type, self.format)
            if not sonraki or sonraki in gorulen:
                return
            gorulen.add(sonraki)
            cursor = sonraki

    def istek(
        self,
        metot: str,
        yol_sorgu: str,
        govde: str = "",
        idempotency_key: Optional[str] = None,
    ) -> YouSoftYanit:
        """Herhangi bir /v1/* servisine imzalı istek gönderir; 429'da Retry-After kadar, GET 5xx'te artan aralıkla tekrar dener."""
        metot = metot.upper()
        bayt = govde.encode("utf-8") if govde else b""
        govde_ozeti = hashlib.sha256(bayt).hexdigest()
        kodlu_yol = urllib.parse.quote(yol_sorgu, safe="/:?=&[]+-._~,%")
        if kodlu_yol.endswith("?") and kodlu_yol.find("?") == len(kodlu_yol) - 1:
            kodlu_yol = kodlu_yol[:-1]
        tam_url = self.taban + kodlu_yol
        parca = urllib.parse.urlsplit(tam_url)
        imzalanacak_yol = f"{parca.path or '/'}?{parca.query}" if parca.query else (parca.path or "/")

        for deneme in range(4):
            ts = str(int(time.time()))
            imza_metni = f"{ts}\n{metot}\n{imzalanacak_yol}\n{govde_ozeti}".encode("utf-8")
            imza = hmac.new(self._secret, imza_metni, hashlib.sha256).hexdigest()

            basliklar = {
                "X-Api-Key": self.api_key,
                "X-Api-Timestamp": ts,
                "X-Api-Signature": imza,
            }
            if self.format == "json":
                basliklar["Accept"] = "application/json"
            if bayt:
                basliklar["Content-Type"] = (
                    "application/json; charset=utf-8"
                    if self.format == "json"
                    else "application/xml; charset=utf-8"
                )
            if idempotency_key:
                basliklar["Idempotency-Key"] = idempotency_key

            req = urllib.request.Request(
                url=tam_url,
                data=bayt if bayt else None,
                headers=basliklar,
                method=metot,
            )

            try:
                with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                    yanit_basliklari = {k.lower(): v for k, v in resp.headers.items()}
                    return YouSoftYanit(
                        status=resp.status,
                        content=resp.read(),
                        content_type=yanit_basliklari.get("content-type", ""),
                        request_id=yanit_basliklari.get("x-request-id", ""),
                        headers=yanit_basliklari,
                    )
            except urllib.error.HTTPError as err:
                yanit_basliklari = {k.lower(): v for k, v in err.headers.items()} if err.headers else {}
                if err.code == 429 and deneme < 3:
                    retry_after = yanit_basliklari.get("retry-after", "1").strip()
                    bekle = max(1, min(60, int(retry_after) if retry_after.isdigit() else 1))
                    err.close()
                    time.sleep(bekle)
                    continue
                if metot == "GET" and err.code in (500, 502, 503, 504) and deneme < 3:
                    err.close()
                    time.sleep(0.5 * (2 ** deneme))
                    continue
                icerik = err.read()
                err.close()
                return YouSoftYanit(
                    status=err.code,
                    content=icerik,
                    content_type=yanit_basliklari.get("content-type", ""),
                    request_id=yanit_basliklari.get("x-request-id", ""),
                    headers=yanit_basliklari,
                )

        raise RuntimeError("Beklenmeyen yeniden deneme durumu.")

    @staticmethod
    def _liste_yolu(taban_yol: str, sorgu: str) -> str:
        temiz = (sorgu or "").strip().lstrip("?")
        return f"{taban_yol}?{temiz}" if temiz else taban_yol

    @staticmethod
    def _yol_parcasi(deger: str) -> str:
        return urllib.parse.quote(str(deger).strip(), safe="")

    @staticmethod
    def _gonderim_mi(govde: str, format_: str) -> bool:
        metin = (govde or "").strip()
        if not metin:
            return False
        if format_ == "json" or metin.startswith("{"):
            try:
                parsed = json.loads(metin)
                return isinstance(parsed, dict) and parsed.get("send") is True
            except Exception:
                return False
        temiz_xml = re.sub(r"<!--[\s\S]*?-->", "", metin)
        return re.search(r"<send>\s*true\s*</send>", temiz_xml, re.IGNORECASE) is not None

    @staticmethod
    def _cursor_temizle(sorgu: str) -> str:
        temiz = (sorgu or "").strip().lstrip("?")
        if not temiz:
            return ""
        parcalar = [p for p in temiz.split("&") if p and not re.match(r"^cursor=", p, re.IGNORECASE)]
        return "&".join(parcalar)

    @staticmethod
    def _sonraki_cursor_oku(metin: str, content_type: str, format_: str) -> str:
        ct = content_type.lower()
        if "xml" not in ct and ("json" in ct or format_ == "json"):
            try:
                parsed = json.loads(metin)
                meta = parsed.get("meta") if isinstance(parsed, dict) else None
                c = meta.get("next_cursor") if isinstance(meta, dict) else None
                return c.strip() if isinstance(c, str) else ""
            except Exception:
                return ""
        m = re.search(r"<meta>[\s\S]*?<next_cursor>([^<]+)</next_cursor>[\s\S]*?</meta>", metin, re.IGNORECASE)
        return m.group(1).strip() if m else ""
