#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""filamentsepeti.app yazıcı bağlantı ajanı.

Ev ağınızdaki 3D yazıcının durumunu okur ve filamentsepeti.app sitesine gönderir.
Site baskının ilerlemesini ve harcanan filamenti gösterir, baskı bitince kaydeder.

Örnekler:
  python3 filamentsepeti_ajan.py --ayar ajan.json
  python3 filamentsepeti_ajan.py --ayar ajan.json --bir-kez
  python3 filamentsepeti_ajan.py --anahtar fs_... --deneme

Ayrıntılar: BENIOKU.md. Gönderilen gövdenin biçimi: docs/yazici-baglantisi.md.
Yalnızca Python 3.9+ standart kitaplığı gerekir; Bambu Lab için ek olarak paho-mqtt.
"""

from __future__ import annotations

import argparse
import collections
import copy
import dataclasses
import email.utils
import ftplib
import hashlib
import http.client
import json
import logging
import logging.handlers
import math
import os
import re
import signal
import socket
import ssl
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ElementTree
import zipfile
from typing import Any, Callable, Deque, Dict, List, Optional, Tuple

SURUM = "1.0.0"
VARSAYILAN_SITE = "https://filamentsepeti.app"
DURUM_YOLU = "/api/yazici/durum"
# Token format issued by the site: "fs_" + 43 base64url characters.
ANAHTAR_DESENI = re.compile(r"^fs_[A-Za-z0-9_-]{43}$")
TURLER = ("bambu", "moonraker", "prusalink", "octoprint")

# Contract states (docs/yazici-baglantisi.md).
STATES = ("idle", "printing", "paused", "finished", "failed", "cancelled", "offline")
ACTIVE_STATES = frozenset(("printing", "paused"))
TERMINAL_STATES = frozenset(("finished", "failed", "cancelled"))
STATE_TR = {
    "idle": "boşta", "printing": "basıyor", "paused": "duraklatıldı", "finished": "bitti",
    "failed": "başarısız", "cancelled": "iptal edildi", "offline": "ulaşılamıyor",
}

MAX_BODY_BYTES = 32 * 1024
SEND_EVERY_ACTIVE = 5.0      # seconds between posts while printing or paused
SEND_EVERY_IDLE = 30.0       # seconds between posts otherwise
MIN_POST_GAP = 2.2           # the site accepts at most one post per 2 s; keep a small margin
AUTH_BACKOFF = 300.0         # wait after 401/404 from the site
SITE_TIMEOUT = 15.0
PRINTER_TIMEOUT = 10.0
OFFLINE_GRACE = 15.0         # report "offline" only after the printer has been unreachable this long
START_TOLERANCE = 300.0      # two printer-reported start times closer than this mean the same print
PENDING_MAX_AGE = 48 * 3600.0
PENDING_MAX = 20
SAVE_EVERY = 60.0
USER_AGENT = "filamentsepeti-ajan/" + SURUM

log = logging.getLogger("filamentsepeti_ajan")


# ---------------------------------------------------------------------------
# Logging: Turkish level names, secrets masked in every line
# ---------------------------------------------------------------------------

_LEVEL_TR = {"DEBUG": "AYRINTI", "INFO": "BİLGİ", "WARNING": "UYARI", "ERROR": "HATA", "CRITICAL": "KRİTİK"}
_SECRETS: set = set()
_TOKEN_LIKE = re.compile(r"fs_[A-Za-z0-9_-]{8,}")


def register_secret(value: Any) -> None:
    """Remember a secret (token, access code, password, API key) so log lines never show it."""
    if isinstance(value, str) and len(value.strip()) >= 4:
        _SECRETS.add(value.strip())


def mask_secrets(text: str) -> str:
    for secret in sorted(_SECRETS, key=len, reverse=True):
        if secret in text:
            text = text.replace(secret, "***")
    # Defence in depth: anything shaped like a site token is masked even if it was never registered.
    return _TOKEN_LIKE.sub("fs_***", text)


class MaskingFormatter(logging.Formatter):
    """Formats with Turkish level names and masks secrets in the final text, tracebacks included."""

    def __init__(self) -> None:
        super().__init__("%(asctime)s %(seviye)s %(message)s", "%Y-%m-%d %H:%M:%S")

    def format(self, record: logging.LogRecord) -> str:
        record.seviye = _LEVEL_TR.get(record.levelname, record.levelname)
        return mask_secrets(super().format(record))


def setup_logging(verbose: bool = False, log_file: Optional[str] = None) -> None:
    log.setLevel(logging.DEBUG if verbose else logging.INFO)
    log.propagate = False
    for handler in list(log.handlers):
        log.removeHandler(handler)
        handler.close()
    if sys.stderr is not None:           # None under pythonw (windowless) on Windows
        stream = logging.StreamHandler(sys.stderr)
        stream.setFormatter(MaskingFormatter())
        log.addHandler(stream)
    if log_file:
        try:
            handler = logging.handlers.RotatingFileHandler(
                log_file, maxBytes=1_000_000, backupCount=3, encoding="utf-8")
        except OSError as err:
            log.warning("Günlük dosyası açılamadı (%s): %s", log_file, err)
        else:
            handler.setFormatter(MaskingFormatter())
            log.addHandler(handler)


class LogThrottle:
    """Logs a message for a key only when the text changes or `every` seconds have passed."""

    def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:
        self._clock = clock
        self._last: Dict[str, Tuple[str, float]] = {}

    def log(self, key: str, level: int, message: str, every: float = 600.0, exc_info: bool = False) -> bool:
        now = self._clock()
        previous = self._last.get(key)
        if previous is not None and previous[0] == message and now - previous[1] < every:
            return False
        self._last[key] = (message, now)
        log.log(level, "%s", message, exc_info=exc_info)
        return True

    def forget(self, key: str) -> bool:
        return self._last.pop(key, None) is not None


# ---------------------------------------------------------------------------
# Errors
# ---------------------------------------------------------------------------

class AyarHatasi(Exception):
    """Invalid configuration; the message is Turkish and shown to the user as is."""


class YaziciOkunamadi(Exception):
    """The printer cannot be read right now (network, not ready, bad answer)."""


class YaziciYetkiHatasi(YaziciOkunamadi):
    """The printer rejected the credentials."""


class HttpDurumHatasi(YaziciOkunamadi):
    def __init__(self, status: int, message: str) -> None:
        super().__init__(message)
        self.status = status


# ---------------------------------------------------------------------------
# Small helpers
# ---------------------------------------------------------------------------

_CONTROL = re.compile(r"[\x00-\x1f\x7f]")
_EXTENSIONS = (".gcode.3mf", ".3mf", ".bgcode", ".gcode", ".gco", ".gc", ".g")


def to_float(value: Any) -> Optional[float]:
    """JSON-ish value to a finite float, or None."""
    if value is None or isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        number = float(value)
    elif isinstance(value, str):
        try:
            number = float(value.strip())
        except ValueError:
            return None
    else:
        return None
    return number if math.isfinite(number) else None


def to_int(value: Any) -> Optional[int]:
    number = to_float(value)
    return int(number) if number is not None else None


def sum_numbers(value: Any) -> Optional[float]:
    """A number, a list of numbers or a "1.2, 3.4" string (per-tool values) summed."""
    if isinstance(value, (list, tuple)):
        parts = [to_float(item) for item in value]
    elif isinstance(value, str) and re.search(r"[,;]", value):
        parts = [to_float(item) for item in re.split(r"[,;]", value)]
    else:
        return to_float(value)
    numbers = [item for item in parts if item is not None]
    return sum(numbers) if numbers else None


def clean_text(value: Any, limit: int) -> Optional[str]:
    if value is None:
        return None
    text = re.sub(r"\s+", " ", _CONTROL.sub(" ", str(value))).strip()
    text = text[:limit].rstrip()
    return text or None


def base_name(path: str) -> str:
    if not path:
        return ""
    return re.split(r"[\\/]", path.rstrip("/\\"))[-1]


def strip_extension(name: str) -> str:
    lowered = name.lower()
    for extension in _EXTENSIONS:
        if lowered.endswith(extension) and len(name) > len(extension):
            return name[: -len(extension)]
    return name


def hex_color(value: Any) -> Optional[str]:
    """'RRGGBBAA', 'RRGGBB' or '#RRGGBB' to '#RRGGBB'."""
    if not isinstance(value, str):
        return None
    text = value.strip().lstrip("#")
    if re.fullmatch(r"[0-9A-Fa-f]{8}", text):
        text = text[:6]
    if re.fullmatch(r"[0-9A-Fa-f]{6}", text):
        return "#" + text.upper()
    return None


def clamp(value: float, low: float, high: float) -> float:
    return max(low, min(high, value))


def materials_text(value: Any) -> Optional[str]:
    """'PLA;PETG' or ['PLA', 'PLA'] to 'PLA/PETG' (unique, in order)."""
    if value is None:
        return None
    items = value if isinstance(value, (list, tuple)) else re.split(r"[;,]", str(value))
    seen: List[str] = []
    for item in items:
        text = clean_text(item, 30)
        if text and text.upper() not in (known.upper() for known in seen):
            seen.append(text)
    return clean_text("/".join(seen), 30) if seen else None


def round_or_none(value: Optional[float], digits: int) -> Optional[float]:
    if value is None or value < 0:
        return None
    return round(value, digits)


def seconds_or_none(value: Optional[float]) -> Optional[int]:
    if value is None:
        return None
    return max(0, int(round(value)))


def describe_error(err: BaseException) -> str:
    """Short Turkish description of a network error."""
    reason = getattr(err, "reason", err)
    if isinstance(reason, ssl.SSLCertVerificationError):
        return "sertifika doğrulanamadı (%s)" % (getattr(reason, "verify_message", "") or reason)
    if isinstance(reason, (socket.timeout, TimeoutError)):
        return "zaman aşımı"
    if isinstance(reason, ConnectionRefusedError):
        return "bağlantı reddedildi"
    if isinstance(reason, socket.gaierror):
        return "adres çözümlenemedi"
    if isinstance(reason, OSError) and reason.strerror:
        return reason.strerror
    text = str(reason) or reason.__class__.__name__
    return text[:200]


# ---------------------------------------------------------------------------
# Contract data
# ---------------------------------------------------------------------------

@dataclasses.dataclass
class JobInfo:
    """A print job as read from the printer, before the agent gives it a contract job id."""
    file_key: str                              # file path/name used to recognise the job
    name: Optional[str] = None
    printer_job_id: Optional[str] = None       # the printer's own job id, if it has one
    start_ts: Optional[float] = None           # start time reported by the printer (epoch s)
    wall_elapsed: Optional[float] = None       # seconds since start including pauses
    progress: Optional[float] = None           # 0-100
    elapsed_sec: Optional[float] = None
    remaining_sec: Optional[float] = None
    planned_grams: Optional[float] = None
    planned_mm: Optional[float] = None
    used_grams: Optional[float] = None
    used_mm: Optional[float] = None
    material: Optional[str] = None


@dataclasses.dataclass
class Snapshot:
    """One reading of the printer."""
    state: str
    job: Optional[JobInfo] = None
    trays: Optional[List[Dict[str, Any]]] = None
    temps: Optional[Dict[str, Optional[float]]] = None
    end_hint: Optional[str] = None             # how the last active job ended, when the adapter knows


def build_body(kind: str, state: str, job: Optional[Dict[str, Any]] = None,
               trays: Optional[List[Dict[str, Any]]] = None,
               temps: Optional[Dict[str, Optional[float]]] = None) -> Dict[str, Any]:
    body: Dict[str, Any] = {"agent": {"version": SURUM, "kind": kind}, "state": state, "job": job}
    if trays is not None:
        body["trays"] = trays
    if temps and any(value is not None for value in temps.values()):
        body["temps"] = {key: (round(value, 1) if value is not None else None)
                         for key, value in temps.items()}
    return body


def encode_body(body: Dict[str, Any]) -> bytes:
    return json.dumps(body, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")


def make_job_id(kind: str, printer_job_id: Optional[str], file_key: str,
                start_ts: Optional[float]) -> str:
    """Job id: the printer's own id when it has one, otherwise file name + start time."""
    parts = [kind]
    if printer_job_id:
        parts.append(str(printer_job_id))
    parts.append(base_name(file_key) or "baski")
    if not printer_job_id and start_ts is not None:
        parts.append(str(int(start_ts)))
    text = "-".join(re.sub(r"\s+", "_", _CONTROL.sub("", part).strip()) for part in parts if part.strip())
    if len(text) > 200:
        digest = hashlib.sha1(text.encode("utf-8")).hexdigest()[:10]
        text = text[:189] + "-" + digest
    return text


def contract_problems(body: Dict[str, Any]) -> List[str]:
    """Checks a body against docs/yazici-baglantisi.md; returns the problems found."""
    problems: List[str] = []
    if body.get("state") not in STATES:
        problems.append("state")
    job = body.get("job", "missing")
    if job == "missing":
        problems.append("job eksik")
    elif job is not None:
        if not isinstance(job, dict):
            problems.append("job nesne değil")
        else:
            if not isinstance(job.get("id"), str) or not job["id"] or len(job["id"]) > 200:
                problems.append("job.id")
            if not isinstance(job.get("name"), str) or len(job["name"]) > 120:
                problems.append("job.name")
            progress = job.get("progress")
            if progress is not None and not (isinstance(progress, (int, float)) and 0 <= progress <= 100):
                problems.append("job.progress")
            for key in ("elapsedSec", "remainingSec", "plannedGrams", "plannedMm", "usedGrams", "usedMm"):
                value = job.get(key)
                if value is not None and not (isinstance(value, (int, float)) and value >= 0):
                    problems.append("job." + key)
            material = job.get("material")
            if material is not None and (not isinstance(material, str) or len(material) > 30):
                problems.append("job.material")
            if "seenRunning" in job and not isinstance(job["seenRunning"], bool):
                problems.append("job.seenRunning")
    try:
        if len(encode_body(body)) > MAX_BODY_BYTES:
            problems.append("gövde 32 KB'tan büyük")
    except ValueError:
        problems.append("gövdede geçersiz sayı")
    return problems


# ---------------------------------------------------------------------------
# Job identity: gives each print a stable id and notices prints that ended unseen
# ---------------------------------------------------------------------------

@dataclasses.dataclass
class TrackedJob:
    id: str
    file_key: str
    printer_job_id: Optional[str]
    start_ts: float
    start_provided: bool
    state: str
    seen_active: bool
    end_sent: bool
    last_seen: float
    last_elapsed: Optional[float]
    last_progress: Optional[float]
    job_body: Dict[str, Any]
    went_offline: bool = False
    restored: bool = False

    def to_json(self) -> Dict[str, Any]:
        data = dataclasses.asdict(self)
        data.pop("restored", None)
        return data

    @classmethod
    def from_json(cls, data: Dict[str, Any]) -> "TrackedJob":
        names = {field.name for field in dataclasses.fields(cls)}
        job = cls(**{key: value for key, value in data.items() if key in names})
        if not isinstance(job.id, str) or not isinstance(job.job_body, dict) or job.state not in STATES:
            raise ValueError("bozuk iş kaydı")
        job.start_ts = float(job.start_ts)
        job.last_seen = float(job.last_seen)
        job.restored = True
        return job


def _norm_key(value: str) -> str:
    return re.sub(r"\s+", " ", (value or "")).strip().casefold()


class JobTracker:
    """Turns adapter snapshots into contract bodies.

    Keeps one job id per print, starts a new id for a new print (even of the same file) and,
    when a print disappears without an end state (the printer went idle or skipped straight
    to another print), produces the end body for it. Bodies that must reach the site exactly
    once (end states) are flagged so the agent can retry them until delivered.
    """

    def __init__(self, kind: str, final_state: Optional[Callable[[TrackedJob], Optional[str]]] = None) -> None:
        self.kind = kind
        self.final_state = final_state
        self.job: Optional[TrackedJob] = None
        self.dirty = False

    # -- persistence -------------------------------------------------------
    def to_json(self) -> Optional[Dict[str, Any]]:
        return self.job.to_json() if self.job else None

    def load(self, data: Any) -> None:
        self.job = None
        if isinstance(data, dict):
            try:
                self.job = TrackedJob.from_json(data)
            except (TypeError, ValueError, KeyError):
                self.job = None

    # -- main entry --------------------------------------------------------
    def process(self, snap: Snapshot, now: float) -> List[Tuple[Dict[str, Any], bool]]:
        out: List[Tuple[Dict[str, Any], bool]] = []
        state = snap.state if snap.state in STATES else "idle"

        if state == "offline":
            if self.job is not None and self.job.state in ACTIVE_STATES and not self.job.went_offline:
                self.job.went_offline = True
                self.dirty = True
            out.append((build_body(self.kind, "offline"), False))
            return out

        info = snap.job if state != "idle" else None
        if info is None and state in ACTIVE_STATES:
            info = JobInfo(file_key="")
        if info is None:
            if self.job is not None and self.job.state in ACTIVE_STATES:
                out.append((self._end(self.job, snap, now), True))
            if self.job is not None:
                self.job = None
                self.dirty = True
            out.append((build_body(self.kind, "idle", None, snap.trays, snap.temps), False))
            return out

        job = self.job
        if job is None or not self._same(job, info, state, now):
            if job is not None and job.state in ACTIVE_STATES:
                out.append((self._end(job, snap, now), True))
            job = self._start(info, now)
        previous = job.state
        self._update(job, info, state, now)
        job.job_body = self._job_dict(job, info, state)
        must_deliver = False
        if state in ACTIVE_STATES:
            job.seen_active = True
            job.end_sent = False
        elif state in TERMINAL_STATES and job.seen_active and not job.end_sent:
            # The site logs the print when it sees this; it must arrive even if the network is down now.
            job.end_sent = True
            must_deliver = True
        if previous != state:
            self.dirty = True
            self._log_transition(job, previous, state)
        out.append((build_body(self.kind, state, job.job_body, snap.trays, snap.temps), must_deliver))
        return out

    # -- internals ---------------------------------------------------------
    def _same(self, job: TrackedJob, info: JobInfo, state: str, now: float) -> bool:
        mine, theirs = job.printer_job_id, info.printer_job_id
        if mine and theirs and mine != theirs:
            return False
        key_a, key_b = _norm_key(job.file_key), _norm_key(info.file_key)
        if key_a and key_b and key_a != key_b:
            return False
        if mine and theirs:
            return not (job.start_provided and info.start_ts is not None
                        and abs(job.start_ts - info.start_ts) > START_TOLERANCE)
        # A print that has ended does not come back: printing again means a new print.
        if job.state in TERMINAL_STATES and state in ACTIVE_STATES:
            return False
        if job.start_provided and info.start_ts is not None:
            return abs(job.start_ts - info.start_ts) <= START_TOLERANCE
        if info.elapsed_sec is not None and job.last_elapsed is not None:
            if info.elapsed_sec + 60 < job.last_elapsed:
                return False          # the time counter went back: the print was restarted
            if job.restored and info.elapsed_sec > job.last_elapsed + max(0.0, now - job.last_seen) + 600:
                return False          # more time passed on the printer than on the clock
        if (state in ACTIVE_STATES and info.progress is not None and job.last_progress is not None
                and info.progress < 5 and job.last_progress - info.progress > 30):
            return False              # progress dropped back to the start
        return True

    def _start(self, info: JobInfo, now: float) -> TrackedJob:
        start = info.start_ts
        provided = start is not None
        if start is None:
            base = info.wall_elapsed if info.wall_elapsed is not None else info.elapsed_sec
            start = now - base if base is not None and base >= 0 else now
        job_id = make_job_id(self.kind, info.printer_job_id, info.file_key or (info.name or ""),
                             None if info.printer_job_id else start)
        job = TrackedJob(id=job_id, file_key=info.file_key or "", printer_job_id=info.printer_job_id,
                         start_ts=float(start), start_provided=provided, state="new", seen_active=False,
                         end_sent=False, last_seen=now, last_elapsed=None, last_progress=None, job_body={})
        self.job = job
        self.dirty = True
        return job

    @staticmethod
    def _update(job: TrackedJob, info: JobInfo, state: str, now: float) -> None:
        if info.printer_job_id and not job.printer_job_id:
            job.printer_job_id = info.printer_job_id
        if info.start_ts is not None and not job.start_provided:
            job.start_ts = float(info.start_ts)
            job.start_provided = True
        if info.file_key and not job.file_key:
            job.file_key = info.file_key
        job.state = state
        job.last_seen = now
        if info.elapsed_sec is not None:
            job.last_elapsed = info.elapsed_sec
        if info.progress is not None:
            job.last_progress = info.progress
        job.restored = False
        job.went_offline = False

    @staticmethod
    def _job_dict(job: TrackedJob, info: JobInfo, state: str) -> Dict[str, Any]:
        progress = info.progress
        remaining = info.remaining_sec
        if state == "finished":
            progress, remaining = 100.0, 0.0
        elif progress is None:
            progress = job.last_progress if job.last_progress is not None else 0.0
        name = (clean_text(info.name, 120)
                or clean_text(strip_extension(base_name(job.file_key)), 120) or "Adsız baskı")
        result: Dict[str, Any] = {
            "id": job.id,
            "name": name,
            "progress": round(clamp(progress, 0.0, 100.0), 1),
            "elapsedSec": seconds_or_none(info.elapsed_sec),
            "remainingSec": seconds_or_none(remaining),
            "plannedGrams": round_or_none(info.planned_grams, 2),
            "plannedMm": round_or_none(info.planned_mm, 1),
            "usedGrams": round_or_none(info.used_grams, 2),
            "usedMm": round_or_none(info.used_mm, 1),
            "material": clean_text(info.material, 30),
        }
        if state in TERMINAL_STATES and job.seen_active:
            # The agent watched this print run: the site logs its end even if it first sees it now.
            result["seenRunning"] = True
        return result

    def _end(self, job: TrackedJob, snap: Snapshot, now: float) -> Dict[str, Any]:
        """End body for a print whose end state the printer never showed."""
        hint = snap.end_hint if snap.end_hint in TERMINAL_STATES else None
        if hint is None and self.final_state is not None:
            try:
                hint = self.final_state(job)
            except Exception as err:  # the lookup is best effort
                log.debug("Bitiş durumu sorgulanamadı: %s", err)
                hint = None
        guessed = hint not in TERMINAL_STATES
        if guessed:
            remaining = job.job_body.get("remainingSec") if job.job_body else None
            if job.went_offline:
                hint = "failed"
            elif (job.last_progress or 0.0) >= 99.0:
                hint = "finished"
            elif job.restored and remaining is not None and now >= job.last_seen + remaining:
                hint = "finished"     # the agent was not running when it ended, and it was due to end
            else:
                hint = "cancelled"
        body_job = dict(job.job_body) if job.job_body else {
            "id": job.id, "name": clean_text(strip_extension(base_name(job.file_key)), 120) or "Adsız baskı",
            "progress": round(clamp(job.last_progress or 0.0, 0.0, 100.0), 1), "elapsedSec": None,
            "remainingSec": None, "plannedGrams": None, "plannedMm": None, "usedGrams": None,
            "usedMm": None, "material": None}
        if hint == "finished":
            body_job["progress"] = 100.0
            body_job["remainingSec"] = 0
        else:
            body_job["remainingSec"] = None
        if job.seen_active:
            body_job["seenRunning"] = True
        job.state = hint
        job.end_sent = True
        job.job_body = body_job
        self.dirty = True
        if guessed:
            log.info("Önceki baskının sonu yazıcıda görülmedi; '%s' olarak bildiriliyor: %s",
                     STATE_TR[hint], body_job.get("name"))
        else:
            log.info("Baskı %s: %s", STATE_TR[hint], body_job.get("name"))
        return build_body(self.kind, hint, body_job)

    @staticmethod
    def _log_transition(job: TrackedJob, previous: str, state: str) -> None:
        name = job.job_body.get("name")
        if previous == "new":
            if state in ACTIVE_STATES:
                log.info("Baskı başladı: %s (iş kimliği: %s)", name, job.id)
            else:
                log.info("Yazıcıda %s bir baskı görünüyor: %s", STATE_TR[state], name)
            return
        messages = {
            "printing": "Baskı devam ediyor: %s", "paused": "Baskı duraklatıldı: %s",
            "finished": "Baskı bitti: %s", "cancelled": "Baskı iptal edildi: %s",
            "failed": "Baskı başarısız oldu: %s",
        }
        if state in messages:
            log.info(messages[state], name)


# ---------------------------------------------------------------------------
# State file: job ids and undelivered end reports survive restarts
# ---------------------------------------------------------------------------

def default_state_path(signature: str) -> str:
    suffix = hashlib.sha1(signature.encode("utf-8")).hexdigest()[:8]
    appdata = os.environ.get("APPDATA") if os.name == "nt" else None
    if appdata:
        return os.path.join(appdata, "filamentsepeti", "ajan-durum-%s.json" % suffix)
    return os.path.join(os.path.expanduser("~"), ".filamentsepeti-ajan-%s.json" % suffix)


class StateStore:
    def __init__(self, path: Optional[str], signature: str, readonly: bool = False) -> None:
        self.path = path
        self.signature = signature
        self.readonly = readonly
        self._warned = False

    def load(self) -> Dict[str, Any]:
        if not self.path:
            return {}
        try:
            with open(self.path, "r", encoding="utf-8") as handle:
                data = json.load(handle)
        except FileNotFoundError:
            return {}
        except (OSError, ValueError) as err:
            log.warning("Durum dosyası okunamadı (%s): %s — yok sayılıyor.", self.path, err)
            return {}
        if not isinstance(data, dict) or data.get("yazici") != self.signature:
            return {}
        return data

    def save(self, data: Dict[str, Any]) -> None:
        if self.readonly or not self.path:
            return
        payload = dict(data, surum=1, yazici=self.signature)
        temp_path = self.path + ".tmp"
        try:
            folder = os.path.dirname(self.path)
            if folder:
                os.makedirs(folder, exist_ok=True)
            descriptor = os.open(temp_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
            with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
                json.dump(payload, handle, ensure_ascii=False)
            os.replace(temp_path, self.path)
            self._warned = False
        except OSError as err:
            if not self._warned:
                log.warning("Durum dosyası yazılamadı (%s): %s. Ajan yeniden başlarsa iş kimlikleri "
                            "korunamayabilir; --durum-dosyasi ile yazılabilir bir yer verin.", self.path, err)
                self._warned = True


# ---------------------------------------------------------------------------
# HTTP: printer client (LAN, optional digest auth) and site client
# ---------------------------------------------------------------------------

_AUTH_PARAM = re.compile(r'([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))')


def parse_auth_params(text: str) -> Dict[str, str]:
    params: Dict[str, str] = {}
    for match in _AUTH_PARAM.finditer(text or ""):
        if match.group(2) is not None:
            value = re.sub(r"\\(.)", r"\1", match.group(2))
        else:
            value = match.group(3)
        params.setdefault(match.group(1).lower(), value)
    return params


class DigestAuth:
    """HTTP Digest authentication (RFC 7616: MD5/SHA-256, qop=auth or none) that reuses the nonce.

    Written here instead of urllib's handler: that one repeats a refused request up to six times,
    which a printer's small web server does not need on every poll.
    """

    def __init__(self, user: str, password: str) -> None:
        self.user = user
        self.password = password
        self.challenge: Optional[Dict[str, str]] = None
        self.nonce_count = 0

    @property
    def ready(self) -> bool:
        return self.challenge is not None

    def update(self, header: str) -> bool:
        """Takes a WWW-Authenticate header; returns True when the server says the old nonce is stale."""
        match = re.search(r"Digest\s+(.*)", header or "", re.I | re.S)
        if not match:
            return False
        params = parse_auth_params(match.group(1))
        if not params.get("nonce"):
            return False
        self.challenge = params
        self.nonce_count = 0
        return params.get("stale", "").lower() == "true"

    def authorization(self, method: str, uri: str, cnonce: Optional[str] = None) -> str:
        challenge = self.challenge or {}
        algorithm = challenge.get("algorithm", "MD5")
        hash_name = "sha256" if algorithm.upper().startswith("SHA-256") else "md5"

        def digest(text: str) -> str:
            return hashlib.new(hash_name, text.encode("utf-8"), usedforsecurity=False).hexdigest()

        realm = challenge.get("realm", "")
        nonce = challenge.get("nonce", "")
        cnonce = cnonce or os.urandom(8).hex()
        ha1 = digest("%s:%s:%s" % (self.user, realm, self.password))
        if algorithm.upper().endswith("-SESS"):
            ha1 = digest("%s:%s:%s" % (ha1, nonce, cnonce))
        ha2 = digest("%s:%s" % (method, uri))
        qops = [item.strip().lower() for item in challenge.get("qop", "").split(",") if item.strip()]

        def quote(value: str) -> str:
            return value.replace("\\", "\\\\").replace('"', '\\"')

        parts = ['username="%s"' % quote(self.user), 'realm="%s"' % quote(realm),
                 'nonce="%s"' % quote(nonce), 'uri="%s"' % quote(uri)]
        if "auth" in qops:
            self.nonce_count += 1
            count = "%08x" % self.nonce_count
            response = digest("%s:%s:%s:%s:auth:%s" % (ha1, nonce, count, cnonce, ha2))
            parts.append('response="%s"' % response)
            parts.extend(["qop=auth", "nc=" + count, 'cnonce="%s"' % cnonce])
        else:
            response = digest("%s:%s:%s" % (ha1, nonce, ha2))
            parts.append('response="%s"' % response)
        if "algorithm" in challenge:
            parts.append("algorithm=%s" % algorithm)
        if "opaque" in challenge:
            parts.append('opaque="%s"' % quote(challenge["opaque"]))
        return "Digest " + ", ".join(parts)


def _read_limited(response: Any, limit: int) -> bytes:
    data = response.read(limit + 1)
    if len(data) > limit:
        raise YaziciOkunamadi("yazıcının cevabı beklenenden büyük")
    return data


class HttpClient:
    """JSON over HTTP for printers on the local network."""

    MAX_RESPONSE = 4 * 1024 * 1024

    def __init__(self, base_url: str, api_key: Optional[str] = None,
                 digest: Optional[Tuple[str, str]] = None, timeout: float = PRINTER_TIMEOUT,
                 opener: Optional[urllib.request.OpenerDirector] = None) -> None:
        self.base = base_url.rstrip("/")
        self.api_key = api_key
        self.digest = DigestAuth(*digest) if digest else None
        self.timeout = timeout
        # The printer is on the LAN: never send these requests through a proxy from the environment.
        self.opener = opener or urllib.request.build_opener(urllib.request.ProxyHandler({}))

    def get_json(self, path: str) -> Tuple[int, Any]:
        status, raw = self._get(path, retry_auth=True)
        if status == 204 or not raw.strip():
            return status, None
        try:
            return status, json.loads(raw.decode("utf-8", errors="replace"))
        except ValueError:
            raise YaziciOkunamadi("yazıcı geçerli JSON döndürmedi (%s)" % path.split("?")[0])

    def _get(self, path: str, retry_auth: bool) -> Tuple[int, bytes]:
        request = urllib.request.Request(self.base + path, method="GET")
        request.add_header("Accept", "application/json")
        request.add_header("User-Agent", USER_AGENT)
        if self.api_key:
            request.add_unredirected_header("X-Api-Key", self.api_key)
        sent_digest = False
        if self.digest is not None and self.digest.ready:
            request.add_unredirected_header("Authorization", self.digest.authorization("GET", request.selector))
            sent_digest = True
        try:
            with self.opener.open(request, timeout=self.timeout) as response:
                return response.status, _read_limited(response, self.MAX_RESPONSE)
        except urllib.error.HTTPError as err:
            try:
                if err.code == 401 and self.digest is not None:
                    stale = self.digest.update((err.headers or {}).get("WWW-Authenticate", ""))
                    if retry_auth and self.digest.ready and (not sent_digest or stale):
                        return self._get(path, retry_auth=False)
                if err.code in (401, 403):
                    raise YaziciYetkiHatasi("yazıcı kimlik bilgilerini kabul etmedi (HTTP %d)" % err.code)
                raise HttpDurumHatasi(err.code, "yazıcı HTTP %d döndürdü (%s)" % (err.code, path.split("?")[0]))
            finally:
                err.close()
        except (urllib.error.URLError, OSError, http.client.HTTPException) as err:
            raise YaziciOkunamadi(describe_error(err))


@dataclasses.dataclass
class SendResult:
    ok: bool
    kind: str                       # ok, auth, bad, too_big, rate, not_found, redirect, server, network, other
    status: Optional[int] = None
    retry_after: Optional[float] = None
    message: str = ""


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    """The token must never follow a redirect to another address."""

    def redirect_request(self, req, fp, code, msg, headers, newurl):  # type: ignore[override]
        return None


def parse_retry_after(value: Optional[str]) -> Optional[float]:
    if not value:
        return None
    text = value.strip()
    if text.isdigit():
        return float(text)
    try:
        moment = email.utils.parsedate_to_datetime(text)
    except (TypeError, ValueError, IndexError):
        return None
    if moment is None:
        return None
    return max(0.0, moment.timestamp() - time.time())


def _error_text(raw: bytes) -> str:
    try:
        data = json.loads(raw.decode("utf-8", errors="replace"))
        if isinstance(data, dict) and data.get("error"):
            return clean_text(data["error"], 300) or ""
    except ValueError:
        pass
    return clean_text(raw.decode("utf-8", errors="replace"), 200) or ""


class SiteClient:
    """Posts status bodies to filamentsepeti.app."""

    def __init__(self, site: str, token: str, timeout: float = SITE_TIMEOUT,
                 opener: Optional[urllib.request.OpenerDirector] = None) -> None:
        self.url = site.rstrip("/") + DURUM_YOLU
        self.token = token
        self.timeout = timeout
        self.opener = opener or urllib.request.build_opener(_NoRedirect())

    def post(self, body: Dict[str, Any]) -> SendResult:
        data = encode_body(body)
        request = urllib.request.Request(self.url, data=data, method="POST")
        request.add_header("Content-Type", "application/json")
        request.add_header("Accept", "application/json")
        request.add_header("User-Agent", USER_AGENT)
        request.add_unredirected_header("Authorization", "Bearer " + self.token)
        try:
            with self.opener.open(request, timeout=self.timeout) as response:
                status = response.status
                headers = response.headers
                raw = response.read(65536)
        except urllib.error.HTTPError as err:
            status, headers = err.code, err.headers
            try:
                raw = err.read(65536)
            except Exception:
                raw = b""
            finally:
                err.close()
        except (urllib.error.URLError, OSError, http.client.HTTPException) as err:
            return SendResult(False, "network", message=describe_error(err))
        return self._classify(status, headers, raw)

    @staticmethod
    def _classify(status: int, headers: Any, raw: bytes) -> SendResult:
        if 200 <= status < 300:
            return SendResult(True, "ok", status)
        message = _error_text(raw)
        if status == 401:
            return SendResult(False, "auth", status, message=message)
        if status == 400:
            return SendResult(False, "bad", status, message=message)
        if status == 413:
            return SendResult(False, "too_big", status, message=message)
        if status == 429:
            retry = parse_retry_after(headers.get("Retry-After") if headers else None)
            return SendResult(False, "rate", status, retry_after=retry, message=message)
        if status == 404:
            return SendResult(False, "not_found", status, message=message)
        if 300 <= status < 400:
            location = headers.get("Location") if headers else None
            return SendResult(False, "redirect", status, message="yönlendirme: %s" % (location or "?"))
        if status >= 500:
            return SendResult(False, "server", status, message="HTTP %d" % status)
        return SendResult(False, "other", status, message=message or "HTTP %d" % status)


class PrintSite:
    """Stands in for the site with --gonderme: prints each body instead of sending it."""

    def __init__(self, out: Any) -> None:
        self.out = out

    def post(self, body: Dict[str, Any]) -> SendResult:
        self.out.write(json.dumps(body, ensure_ascii=False) + "\n")
        self.out.flush()
        return SendResult(True, "ok", 0)


# ---------------------------------------------------------------------------
# Adapters
# ---------------------------------------------------------------------------

class Adapter:
    kind = "?"
    poll_interval = 5.0      # seconds between readings
    network_poll = True      # readings go over the network: back off when the printer is unreachable
    ready_timeout = 0.0      # --bir-kez: how long to wait for the first reading

    def start(self) -> None:
        pass

    def stop(self) -> None:
        pass

    def read(self) -> Snapshot:
        raise NotImplementedError

    def final_state(self, job: TrackedJob) -> Optional[str]:
        """How a print that vanished ended, if the printer can tell afterwards."""
        return None

    def describe(self) -> str:
        return self.kind


def printer_base_url(address: str, default_port: Optional[int] = None) -> str:
    text = (address or "").strip()
    if not text:
        raise AyarHatasi("Yazıcı adresi eksik: --adres 192.168.1.50 (ayar dosyasında \"adres\").")
    if "://" not in text:
        host = text.strip("/")
        if host.count(":") >= 2 and not host.startswith("["):
            host = "[%s]" % host        # bare IPv6 address
        if default_port and not re.search(r":\d+$", host):
            host += ":%d" % default_port
        text = "http://" + host
    parsed = urllib.parse.urlparse(text)
    if parsed.scheme not in ("http", "https") or not parsed.hostname:
        raise AyarHatasi("Yazıcı adresi anlaşılamadı: %s (örnek: 192.168.1.50 ya da http://192.168.1.50)" % address)
    return text.rstrip("/")


# --- Moonraker (Klipper) ---------------------------------------------------

class MoonrakerAdapter(Adapter):
    kind = "moonraker"
    OBJECTS = ("webhooks", "print_stats", "virtual_sdcard", "extruder", "heater_bed",
               "heater_generic chamber", "temperature_sensor chamber")
    STATE_MAP = {"standby": "idle", "printing": "printing", "paused": "paused",
                 "complete": "finished", "error": "failed", "cancelled": "cancelled"}
    HISTORY_STATUS = {"completed": "finished", "cancelled": "cancelled", "error": "failed",
                      "klippy_shutdown": "failed", "klippy_disconnect": "failed", "interrupted": "failed"}

    def __init__(self, base_url: str, api_key: Optional[str] = None, http: Optional[HttpClient] = None,
                 clock: Callable[[], float] = time.monotonic, wall: Callable[[], float] = time.time) -> None:
        self.http = http or HttpClient(base_url, api_key=api_key)
        self.clock = clock
        self.wall = wall
        self._ctx: Optional[Dict[str, Any]] = None
        self._history: Optional[bool] = None      # None: not known yet

    def describe(self) -> str:
        return "Moonraker (%s)" % self.http.base

    def read(self) -> Snapshot:
        query = "&".join(urllib.parse.quote(name) for name in self.OBJECTS)
        _, data = self.http.get_json("/printer/objects/query?" + query)
        status = ((data or {}).get("result") or {}).get("status") if isinstance(data, dict) else None
        if not isinstance(status, dict):
            raise YaziciOkunamadi("Moonraker beklenmeyen bir cevap verdi")
        hooks = status.get("webhooks") or {}
        klippy = hooks.get("state")
        if klippy is not None and klippy != "ready":
            detail = clean_text(hooks.get("state_message"), 120)
            raise YaziciOkunamadi("Klipper hazır değil (%s)%s" % (klippy, ": " + detail if detail else ""))
        stats = status.get("print_stats") or {}
        sdcard = status.get("virtual_sdcard") or {}
        temps = self._temps(status)
        state = self.STATE_MAP.get(str(stats.get("state") or ""), "idle")
        filename = str(stats.get("filename") or "")
        if state == "idle" or not filename:
            self._ctx = None
            return Snapshot("idle", None, None, temps)

        ctx = self._context(filename, state, stats)
        self._load_metadata(ctx)
        self._load_history(ctx, state, stats)
        meta = ctx["meta"] or {}
        history = ctx["hist"] or {}

        fraction = to_float(sdcard.get("progress"))
        progress = clamp(fraction * 100.0, 0.0, 100.0) if fraction is not None else None
        print_duration = to_float(stats.get("print_duration"))
        estimated = to_float(meta.get("estimated_time"))
        if state == "finished":
            remaining: Optional[float] = 0.0
        elif state in TERMINAL_STATES:
            remaining = None
        elif estimated and print_duration is not None:
            remaining = max(0.0, estimated - print_duration)
        elif fraction and fraction > 0.01 and print_duration:
            remaining = max(0.0, print_duration / fraction - print_duration)
        else:
            remaining = None
        info = JobInfo(
            file_key=filename,
            name=strip_extension(base_name(filename)),
            printer_job_id=history.get("job_id"),
            start_ts=history.get("start"),
            wall_elapsed=to_float(stats.get("total_duration")),
            progress=progress,
            elapsed_sec=print_duration,
            remaining_sec=remaining,
            planned_grams=to_float(meta.get("filament_weight_total")),
            planned_mm=to_float(meta.get("filament_total")),
            used_mm=to_float(stats.get("filament_used")),
            material=materials_text(meta.get("filament_type")),
        )
        return Snapshot(state, info, None, temps)

    @staticmethod
    def _temps(status: Dict[str, Any]) -> Dict[str, Optional[float]]:
        def temperature(name: str) -> Optional[float]:
            obj = status.get(name)
            return to_float(obj.get("temperature")) if isinstance(obj, dict) else None

        chamber = temperature("heater_generic chamber")
        if chamber is None:
            chamber = temperature("temperature_sensor chamber")
        return {"nozzle": temperature("extruder"), "bed": temperature("heater_bed"), "chamber": chamber}

    def _context(self, filename: str, state: str, stats: Dict[str, Any]) -> Dict[str, Any]:
        total = to_float(stats.get("total_duration"))
        ctx = self._ctx
        new_job = (ctx is None or ctx["filename"] != filename
                   or (state in ACTIVE_STATES and ctx["state"] not in ACTIVE_STATES)
                   or (total is not None and ctx["total"] is not None and total + 30 < ctx["total"]))
        if new_job:
            ctx = {"filename": filename, "state": state, "total": total,
                   "meta": None, "meta_tries": 0, "meta_next": 0.0, "meta_done": False,
                   "hist": None, "hist_tries": 0, "hist_next": 0.0, "hist_done": False}
            self._ctx = ctx
        assert ctx is not None
        ctx["state"] = state
        if total is not None:
            ctx["total"] = total
        return ctx

    def _load_metadata(self, ctx: Dict[str, Any]) -> None:
        if ctx["meta_done"] or self.clock() < ctx["meta_next"]:
            return
        ctx["meta_tries"] += 1
        try:
            _, data = self.http.get_json(
                "/server/files/metadata?" + urllib.parse.urlencode({"filename": ctx["filename"]}))
            meta = data.get("result") if isinstance(data, dict) else None
            if isinstance(meta, dict):
                ctx["meta"] = meta
                ctx["meta_done"] = True
                return
        except HttpDurumHatasi as err:
            if err.status == 404:
                ctx["meta_done"] = True
                log.debug("Moonraker dosya bilgisi yok: %s", ctx["filename"])
                return
        except YaziciOkunamadi as err:
            log.debug("Moonraker dosya bilgisi okunamadı: %s", err)
        if ctx["meta_tries"] >= 5:
            ctx["meta_done"] = True
        else:
            ctx["meta_next"] = self.clock() + 30.0

    def _load_history(self, ctx: Dict[str, Any], state: str, stats: Dict[str, Any]) -> None:
        if self._history is False or ctx["hist_done"] or self.clock() < ctx["hist_next"]:
            return
        ctx["hist_tries"] += 1
        try:
            _, data = self.http.get_json("/server/history/list?limit=1&order=desc")
        except HttpDurumHatasi as err:
            if err.status in (400, 404):
                self._history = False
                log.info("Moonraker iş geçmişi (history) açık değil; iş kimliği dosya adı ve başlama "
                         "zamanından üretilecek.")
                return
        except YaziciOkunamadi as err:
            log.debug("Moonraker iş geçmişi okunamadı: %s", err)
        else:
            self._history = True
            jobs = ((data or {}).get("result") or {}).get("jobs") if isinstance(data, dict) else None
            latest = jobs[0] if isinstance(jobs, list) and jobs and isinstance(jobs[0], dict) else None
            if latest is not None and self._history_matches(latest, ctx, state, stats):
                ctx["hist"] = {"job_id": str(latest["job_id"]), "start": to_float(latest.get("start_time"))}
                ctx["hist_done"] = True
                return
        if ctx["hist_tries"] >= 3:
            ctx["hist_done"] = True
        else:
            ctx["hist_next"] = self.clock() + 5.0

    def _history_matches(self, entry: Dict[str, Any], ctx: Dict[str, Any], state: str,
                         stats: Dict[str, Any]) -> bool:
        if str(entry.get("filename") or "") != ctx["filename"] or not entry.get("job_id"):
            return False
        if state in ACTIVE_STATES:
            if entry.get("status") != "in_progress":
                return False
            total = to_float(stats.get("total_duration"))
            start = to_float(entry.get("start_time"))
            if total is not None and start is not None and abs((self.wall() - total) - start) > START_TOLERANCE:
                return False
        return True

    def final_state(self, job: TrackedJob) -> Optional[str]:
        if not job.printer_job_id or self._history is not True:
            return None
        try:
            _, data = self.http.get_json(
                "/server/history/job?" + urllib.parse.urlencode({"uid": job.printer_job_id}))
        except YaziciOkunamadi:
            return None
        entry = ((data or {}).get("result") or {}).get("job") if isinstance(data, dict) else None
        if not isinstance(entry, dict):
            return None
        return self.HISTORY_STATUS.get(str(entry.get("status") or ""))


# --- PrusaLink (MK4, CORE One, XL, MINI; MK3 with PrusaLink) --------------

class PrusaLinkAdapter(Adapter):
    kind = "prusalink"
    STATE_MAP = {"PRINTING": "printing", "BUSY": "printing", "PAUSED": "paused", "ATTENTION": "paused",
                 "FINISHED": "finished", "STOPPED": "cancelled", "ERROR": "failed"}

    def __init__(self, base_url: str, user: str = "maker", password: Optional[str] = None,
                 api_key: Optional[str] = None, http: Optional[HttpClient] = None) -> None:
        digest = (user or "maker", password) if password else None
        self.http = http or HttpClient(base_url, api_key=None if password else api_key, digest=digest)
        self._jobs: Dict[str, Dict[str, Any]] = {}

    def describe(self) -> str:
        return "PrusaLink (%s)" % self.http.base

    def read(self) -> Snapshot:
        _, status = self.http.get_json("/api/v1/status")
        if not isinstance(status, dict) or not isinstance(status.get("printer"), dict):
            raise YaziciOkunamadi("PrusaLink beklenmeyen bir cevap verdi")
        printer = status["printer"]
        temps = {"nozzle": to_float(printer.get("temp_nozzle")), "bed": to_float(printer.get("temp_bed")),
                 "chamber": to_float(printer.get("temp_chamber"))}
        job_status = status.get("job") if isinstance(status.get("job"), dict) else None
        job_id = job_status.get("id") if job_status else None
        state = self.STATE_MAP.get(str(printer.get("state") or "").upper(), "idle")
        if job_id is None or state == "idle":
            return Snapshot("idle", None, None, temps)
        assert job_status is not None
        job_key = str(job_id)
        details = self._job_details(job_key)
        file_info = (details or {}).get("file") if isinstance((details or {}).get("file"), dict) else {}
        meta = file_info.get("meta") if isinstance(file_info.get("meta"), dict) else {}
        display = str(file_info.get("display_name") or file_info.get("name") or "")
        folder = str(file_info.get("path") or "")
        info = JobInfo(
            file_key=(folder.rstrip("/") + "/" + display) if display else "",
            name=strip_extension(display) if display else None,
            printer_job_id=job_key,
            progress=to_float(job_status.get("progress")),
            elapsed_sec=to_float(job_status.get("time_printing")),
            remaining_sec=to_float(job_status.get("time_remaining")) if state in ACTIVE_STATES else None,
            # Only PrusaLink on a Raspberry Pi (MK3) reports G-code metadata; the printers' own
            # firmware does not, so these stay empty there.
            planned_grams=sum_numbers(meta.get("filament used [g]")),
            planned_mm=sum_numbers(meta.get("filament used [mm]")),
            material=materials_text(meta.get("filament_type")),
        )
        return Snapshot(state, info, None, temps)

    def _job_details(self, job_key: str) -> Optional[Dict[str, Any]]:
        if job_key in self._jobs:
            return self._jobs[job_key]
        try:
            status, data = self.http.get_json("/api/v1/job")
        except YaziciYetkiHatasi:
            raise
        except YaziciOkunamadi as err:
            log.debug("PrusaLink iş bilgisi okunamadı: %s", err)
            return None
        if status == 204 or not isinstance(data, dict) or str(data.get("id")) != job_key:
            return None
        self._jobs = {job_key: data}
        return data


# --- OctoPrint --------------------------------------------------------------

def octoprint_filament_length(filament: Any) -> Optional[float]:
    """Total of job.filament.<tool>.length (mm) over all tools."""
    total = 0.0
    found = False

    def visit(node: Any, depth: int) -> None:
        nonlocal total, found
        if not isinstance(node, dict) or depth > 3:
            return
        length = to_float(node.get("length"))
        if length is not None:
            total += length
            found = True
            return
        for child in node.values():
            visit(child, depth + 1)

    visit(filament, 0)
    return total if found else None


class OctoPrintAdapter(Adapter):
    kind = "octoprint"
    TRANSFER_STATES = ("Sending file to SD", "Transferring file to SD", "Starting to send file to SD")
    PRINTING_STATES = ("Printing", "Printing from SD", "Starting", "Starting print from SD",
                       "Resuming", "Finishing", "Cancelling")
    DISCONNECTED_PREFIXES = ("offline", "closed", "opening serial", "detecting serial", "connecting")

    def __init__(self, base_url: str, api_key: str, http: Optional[HttpClient] = None) -> None:
        self.http = http or HttpClient(base_url, api_key=api_key)
        self._active: Optional[JobInfo] = None
        self._cancel_seen = False
        self._last_end: Optional[str] = None

    def describe(self) -> str:
        return "OctoPrint (%s)" % self.http.base

    def read(self) -> Snapshot:
        _, job_resp = self.http.get_json("/api/job")
        if not isinstance(job_resp, dict):
            raise YaziciOkunamadi("OctoPrint beklenmeyen bir cevap verdi")
        printer: Dict[str, Any] = {}
        try:
            _, data = self.http.get_json("/api/printer?exclude=sd")
            if isinstance(data, dict):
                printer = data
        except HttpDurumHatasi as err:
            if err.status != 409:     # 409: the printer is not connected to OctoPrint
                raise
        text = str(job_resp.get("state") or "")
        lowered = text.lower()
        flags = ((printer.get("state") or {}).get("flags") or {}) if isinstance(printer.get("state"), dict) else {}
        temps = self._temps(printer)

        job = job_resp.get("job") if isinstance(job_resp.get("job"), dict) else {}
        progress = job_resp.get("progress") if isinstance(job_resp.get("progress"), dict) else {}
        file_info = job.get("file") if isinstance(job.get("file"), dict) else {}
        path = str(file_info.get("path") or file_info.get("name") or "")
        display = str(file_info.get("display") or file_info.get("name") or "")
        completion = to_float(progress.get("completion"))
        planned_mm = octoprint_filament_length(job.get("filament"))
        info: Optional[JobInfo] = None
        if path:
            info = JobInfo(
                file_key="%s/%s" % (file_info.get("origin") or "local", path.lstrip("/")),
                name=strip_extension(base_name(display)) if display else None,
                progress=completion,
                elapsed_sec=to_float(progress.get("printTime")),
                remaining_sec=to_float(progress.get("printTimeLeft")),
                planned_mm=planned_mm,
                # OctoPrint does not measure extrusion: estimate from the planned length and progress.
                used_mm=(planned_mm * clamp(completion, 0.0, 100.0) / 100.0
                         if planned_mm is not None and completion is not None else None),
            )

        error = bool(flags.get("error")) or lowered.startswith("error") or "after error" in lowered
        disconnected = (not error and lowered.startswith(self.DISCONNECTED_PREFIXES)) or (
            bool(flags.get("closedOrError")) and not error and not flags.get("operational"))
        transfer = text in self.TRANSFER_STATES
        paused = bool(flags.get("paused") or flags.get("pausing")) or text in ("Paused", "Pausing")
        printing = not transfer and (bool(flags.get("printing") or flags.get("cancelling") or flags.get("finishing"))
                                     or text in self.PRINTING_STATES)
        if flags.get("cancelling") or text == "Cancelling":
            self._cancel_seen = True

        if (printing or paused) and not error and not disconnected and info is not None:
            self._active = info
            return Snapshot("paused" if paused else "printing", info, None, temps)

        if self._active is not None:
            # The print just stopped: OctoPrint has no lasting end state, so work it out once.
            if error or disconnected:
                self._last_end = "failed"
            elif completion is not None and completion >= 99.9:
                self._last_end = "finished"
            else:
                self._last_end = "cancelled"
            self._active = None
            self._cancel_seen = False

        if disconnected or (error and not flags.get("operational")):
            return Snapshot("offline", end_hint=self._last_end)
        if info is not None and completion is not None and completion >= 99.9 and not error:
            # After a completed print OctoPrint keeps the file selected at 100 %.
            return Snapshot("finished", info, None, temps, end_hint=self._last_end)
        return Snapshot("idle", None, None, temps, end_hint=self._last_end)

    @staticmethod
    def _temps(printer: Dict[str, Any]) -> Dict[str, Optional[float]]:
        temperature = printer.get("temperature") if isinstance(printer.get("temperature"), dict) else {}

        def actual(name: str) -> Optional[float]:
            entry = temperature.get(name)
            return to_float(entry.get("actual")) if isinstance(entry, dict) else None

        return {"nozzle": actual("tool0"), "bed": actual("bed"), "chamber": actual("chamber")}


# --- Bambu Lab (LAN MQTT, optional FTPS) -----------------------------------

BAMBU_CANCEL_ERROR = 50348044          # print_error reported when the user stops a print
BAMBU_STATES = {"IDLE": "idle", "PREPARE": "printing", "SLICING": "printing", "RUNNING": "printing",
                "PAUSE": "paused", "FINISH": "finished", "FAILED": "failed"}


def _find_by_id(items: List[Any], item_id: Any) -> Optional[Dict[str, Any]]:
    for item in items:
        if isinstance(item, dict) and str(item.get("id")) == str(item_id):
            return item
    return None


def _merge_trays(unit: Dict[str, Any], trays: List[Any]) -> None:
    current = unit.get("tray") if isinstance(unit.get("tray"), list) else []
    unit["tray"] = current
    for tray in trays:
        if not isinstance(tray, dict) or "id" not in tray:
            continue
        existing = _find_by_id(current, tray["id"])
        if set(tray.keys()) <= {"id", "state"}:
            # An empty slot is reported with its id only: forget what was loaded there.
            replacement = copy.deepcopy(tray)
            if existing is None:
                current.append(replacement)
            else:
                existing.clear()
                existing.update(replacement)
        elif existing is None:
            current.append(copy.deepcopy(tray))
        else:
            existing.update(copy.deepcopy(tray))


def _merge_ams(target: Dict[str, Any], update: Dict[str, Any]) -> None:
    for key, value in update.items():
        if key == "ams" and isinstance(value, list):
            units = target.get("ams") if isinstance(target.get("ams"), list) else []
            target["ams"] = units
            for unit in value:
                if not isinstance(unit, dict) or "id" not in unit:
                    continue
                existing = _find_by_id(units, unit["id"])
                if existing is None:
                    existing = {"id": unit["id"]}
                    units.append(existing)
                for unit_key, unit_value in unit.items():
                    if unit_key == "tray" and isinstance(unit_value, list):
                        _merge_trays(existing, unit_value)
                    else:
                        existing[unit_key] = copy.deepcopy(unit_value)
        else:
            target[key] = copy.deepcopy(value)
    bits = target.get("ams_exist_bits")
    if isinstance(bits, str) and isinstance(target.get("ams"), list):
        try:
            mask = int(bits, 16)
        except ValueError:
            return
        target["ams"] = [unit for unit in target["ams"]
                         if to_int(unit.get("id")) is None or to_int(unit.get("id")) >= 16
                         or mask & (1 << to_int(unit.get("id")))]


def _deep_merge(target: Dict[str, Any], update: Dict[str, Any]) -> None:
    for key, value in update.items():
        if isinstance(value, dict) and isinstance(target.get(key), dict):
            _deep_merge(target[key], value)
        elif (key == "info" and isinstance(value, list) and isinstance(target.get(key), list)
              and all(isinstance(item, dict) and "id" in item for item in value)):
            for item in value:             # device.extruder.info entries, one per nozzle
                existing = _find_by_id(target[key], item["id"])
                if existing is None:
                    target[key].append(copy.deepcopy(item))
                else:
                    existing.update(copy.deepcopy(item))
        else:
            target[key] = copy.deepcopy(value)


def merge_bambu_report(state: Dict[str, Any], update: Dict[str, Any]) -> None:
    """Merges one `print` report into the accumulated state (P1/A1 send only what changed)."""
    for key, value in update.items():
        if key == "ams" and isinstance(value, dict):
            if not isinstance(state.get("ams"), dict):
                state["ams"] = {}
            _merge_ams(state["ams"], value)
        elif isinstance(value, dict) and isinstance(state.get(key), dict):
            _deep_merge(state[key], value)
        else:
            state[key] = copy.deepcopy(value)


def _packed_low(value: Any) -> Optional[float]:
    """New firmware packs temperatures as (target << 16) | current."""
    number = to_int(value)
    return float(number & 0xFFFF) if number is not None else None


class BambuModel:
    """The printer's merged status and its mapping to the contract (no network here)."""

    def __init__(self) -> None:
        self.data: Dict[str, Any] = {}
        self.reports = 0
        self._last_gstate: Optional[str] = None
        self._cancel_key: Optional[Tuple[str, str, str]] = None
        self._ended_sig: Optional[Tuple[str, str]] = None
        self._ended_at: Optional[Tuple[Tuple[str, str, str], float]] = None

    # -- feeding -----------------------------------------------------------
    def feed(self, update: Dict[str, Any], now: float) -> None:
        merge_bambu_report(self.data, update)
        self.reports += 1
        if to_int(update.get("print_error")) == BAMBU_CANCEL_ERROR:
            # Stopping a print shows as FAILED; this error code, sent for a few seconds, marks it as a cancel.
            self._cancel_key = self.job_key()
        gstate = self.gstate()
        if gstate != self._last_gstate:
            if gstate in ("FINISH", "FAILED"):
                self._ended_at = (self.job_key(), now)
            if gstate in ("FINISH", "FAILED", "IDLE"):
                # Remember the ended job's ids: right after a new print starts the printer may still
                # report them for a moment, and they must not be taken for the new print's ids.
                self._ended_sig = (self._task_id(), str(self.data.get("gcode_start_time") or ""))
            self._last_gstate = gstate

    @property
    def empty(self) -> bool:
        return not self.data

    def gstate(self) -> str:
        return str(self.data.get("gcode_state") or "").upper()

    def _task_id(self) -> str:
        value = str(self.data.get("task_id") or "").strip()
        return "" if value in ("", "0") else value

    def file_info(self) -> Tuple[str, Optional[str]]:
        subtask = clean_text(self.data.get("subtask_name"), 200) or ""
        gcode_file = clean_text(self.data.get("gcode_file"), 200) or ""
        if subtask:
            name = strip_extension(base_name(subtask))
            return name, name
        if gcode_file and "metadata/" not in gcode_file.lower():
            name = strip_extension(base_name(gcode_file))
            return name, name
        return "", None

    def job_key(self) -> Tuple[str, str, str]:
        return (self.file_info()[0], self._task_id(), str(self.data.get("gcode_start_time") or ""))

    def plate_index(self) -> Optional[int]:
        match = re.search(r"plate_(\d+)\.gcode", str(self.data.get("gcode_file") or ""), re.I)
        if match:
            return int(match.group(1))
        plate = to_int(self.data.get("plate_idx"))
        return plate if plate and plate > 0 else None

    # -- mapping -----------------------------------------------------------
    def snapshot(self, now: float, meta: Optional[Dict[str, Any]] = None) -> Snapshot:
        gstate = self.gstate()
        state = BAMBU_STATES.get(gstate, "idle")
        if state == "failed" and self._cancel_key is not None and self._cancel_key == self.job_key():
            state = "cancelled"
        trays = self.trays()
        temps = self.temps()
        if state == "idle":
            return Snapshot("idle", None, trays, temps)

        file_key, name = self.file_info()
        task = self._task_id()
        start_raw = str(self.data.get("gcode_start_time") or "")
        start = to_int(start_raw)
        if state in ACTIVE_STATES and self._ended_sig is not None:
            if task and task == self._ended_sig[0]:
                task = ""
            if start_raw and start_raw == self._ended_sig[1]:
                start = None
        if start is not None and not (1_000_000_000 < start <= now + 86400):
            start = None

        progress = to_float(self.data.get("mc_percent"))
        remaining = to_float(self.data.get("mc_remaining_time"))
        remaining = remaining * 60.0 if remaining is not None and remaining >= 0 else None
        if gstate == "PREPARE":
            progress = 0.0
        if state == "finished":
            progress, remaining = 100.0, 0.0
        elif state in TERMINAL_STATES:
            remaining = None

        elapsed = None
        if start is not None:
            end: Optional[float] = now
            if state in TERMINAL_STATES:
                end = self._ended_at[1] if self._ended_at and self._ended_at[0] == self.job_key() else None
            if end is not None:
                elapsed = max(0.0, end - start)

        meta = meta or {}
        material = meta.get("material") or next(
            (tray["material"] for tray in trays if tray.get("active")), None)
        info = JobInfo(
            file_key=file_key,
            name=name,
            printer_job_id=task or None,
            start_ts=float(start) if start is not None else None,
            progress=progress,
            elapsed_sec=elapsed,
            remaining_sec=remaining,
            planned_grams=to_float(meta.get("planned_grams")),
            planned_mm=to_float(meta.get("planned_mm")),
            material=material,
        )
        return Snapshot(state, info, trays, temps)

    def _active_slots(self) -> Tuple[Optional[int], List[Tuple[int, int]]]:
        ams = self.data.get("ams") if isinstance(self.data.get("ams"), dict) else {}
        tray_now = to_int(ams.get("tray_now"))
        pairs: List[Tuple[int, int]] = []
        device = self.data.get("device") if isinstance(self.data.get("device"), dict) else {}
        extruder = device.get("extruder") if isinstance(device.get("extruder"), dict) else {}
        entries = extruder.get("info") if isinstance(extruder.get("info"), list) else []
        packed_state = to_int(extruder.get("state"))
        active_nozzle = (packed_state >> 4) & 0xF if packed_state is not None else None
        for entry in entries:
            if not isinstance(entry, dict):
                continue
            if len(entries) > 1 and active_nozzle is not None and to_int(entry.get("id")) != active_nozzle:
                continue
            slot = to_int(entry.get("snow"))
            if slot is not None and slot not in (0xFF, 0xFFFF):
                pairs.append((slot >> 8, slot & 0xFF))
        return tray_now, pairs

    def trays(self) -> List[Dict[str, Any]]:
        tray_now, pairs = self._active_slots()
        result: List[Dict[str, Any]] = []
        ams = self.data.get("ams") if isinstance(self.data.get("ams"), dict) else {}
        units = ams.get("ams") if isinstance(ams.get("ams"), list) else []
        for unit in units:
            if not isinstance(unit, dict):
                continue
            unit_id = to_int(unit.get("id"))
            if unit_id is None:
                continue
            for tray in unit.get("tray") or []:
                if not isinstance(tray, dict):
                    continue
                tray_id = to_int(tray.get("id"))
                material = clean_text(tray.get("tray_type"), 30)
                if tray_id is None or not material:
                    continue                          # empty slot
                if unit_id >= 128:                    # AMS HT: one slot per unit, ids from 128
                    slot, overall = "HT%d" % (unit_id - 127), unit_id
                elif unit_id < 26:
                    slot, overall = "%s%d" % (chr(ord("A") + unit_id), tray_id + 1), unit_id * 4 + tray_id
                else:
                    continue
                active = tray_now == overall or (unit_id, tray_id) in pairs
                result.append(self._tray(slot, material, tray, active))
        externals = self.data.get("vir_slot")
        if isinstance(externals, list) and externals:
            for position, tray in enumerate(externals):
                if not isinstance(tray, dict):
                    continue
                material = clean_text(tray.get("tray_type"), 30)
                if not material:
                    continue
                slot_id = to_int(tray.get("id"))
                slot = "Harici" if len(externals) == 1 else "Harici %d" % (position + 1)
                active = (slot_id is not None and (slot_id, 0) in pairs) or (
                    tray_now == 254 and position == 0 and not pairs)
                result.append(self._tray(slot, material, tray, active))
        elif isinstance(self.data.get("vt_tray"), dict):
            tray = self.data["vt_tray"]
            material = clean_text(tray.get("tray_type"), 30)
            if material:
                result.append(self._tray("Harici", material, tray, tray_now == 254))
        return result

    @staticmethod
    def _tray(slot: str, material: str, tray: Dict[str, Any], active: bool) -> Dict[str, Any]:
        remain = to_int(tray.get("remain"))
        return {"slot": slot, "material": material, "color": hex_color(tray.get("tray_color")),
                "remainPct": int(clamp(remain, 0, 100)) if remain is not None and remain >= 0 else None,
                "active": bool(active)}

    def temps(self) -> Dict[str, Optional[float]]:
        device = self.data.get("device") if isinstance(self.data.get("device"), dict) else {}
        nozzle = None
        extruder = device.get("extruder") if isinstance(device.get("extruder"), dict) else {}
        entries = [entry for entry in (extruder.get("info") or []) if isinstance(entry, dict)] \
            if isinstance(extruder.get("info"), list) else []
        if entries:
            packed_state = to_int(extruder.get("state"))
            active_nozzle = (packed_state >> 4) & 0xF if packed_state is not None else None
            chosen = next((entry for entry in entries if to_int(entry.get("id")) == active_nozzle), entries[0])
            nozzle = _packed_low(chosen.get("temp"))
        if nozzle is None:
            nozzle = to_float(self.data.get("nozzle_temper"))
        bed_info = (device.get("bed") or {}).get("info") if isinstance(device.get("bed"), dict) else None
        bed = _packed_low(bed_info.get("temp")) if isinstance(bed_info, dict) else None
        if bed is None:
            bed = to_float(self.data.get("bed_temper"))
        # Chamber only where the printer has a sensor block for it; older P1/A1 payloads carry a
        # chamber_temper value even without a sensor, so that field is not used.
        ctc_info = (device.get("ctc") or {}).get("info") if isinstance(device.get("ctc"), dict) else None
        chamber = _packed_low(ctc_info.get("temp")) if isinstance(ctc_info, dict) else None
        return {"nozzle": nozzle, "bed": bed, "chamber": chamber}


def printer_tls_context() -> ssl.SSLContext:
    """TLS for the printer only.

    Bambu printers present a certificate from Bambu's own CA, which the system does not trust,
    so verification is switched off for this connection and nowhere else; the site connection
    keeps full verification. --bambu-sertifika can pin the printer's certificate.
    """
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE
    try:
        # Some printer firmware never answers a TLS 1.3 hello.
        context.maximum_version = ssl.TLSVersion.TLSv1_2
    except (AttributeError, ValueError):
        pass
    return context


def certificate_sha256(sock: Any) -> Optional[str]:
    try:
        der = sock.getpeercert(binary_form=True)
    except (AttributeError, ValueError, OSError):
        return None
    return hashlib.sha256(der).hexdigest() if der else None


def colon_hex(digest: str) -> str:
    return ":".join(digest[i:i + 2] for i in range(0, len(digest), 2)).upper()


class ImplicitFTPS(ftplib.FTP_TLS):
    """FTP over implicit TLS (port 990) as used by Bambu printers.

    The data channel reuses the control channel's TLS session, which the printer requires.
    """

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        self._sock: Any = None

    @property
    def sock(self) -> Any:  # type: ignore[override]
        return self._sock

    @sock.setter
    def sock(self, value: Any) -> None:
        if value is not None and not isinstance(value, ssl.SSLSocket):
            value = self.context.wrap_socket(value, server_hostname=self.host)
        self._sock = value

    def ntransfercmd(self, cmd: str, rest: Any = None) -> Tuple[Any, Optional[int]]:
        conn, size = ftplib.FTP.ntransfercmd(self, cmd, rest)
        if self._prot_p:
            session = self.sock.session if isinstance(self.sock, ssl.SSLSocket) else None
            conn = self.context.wrap_socket(conn, server_hostname=self.host, session=session)
        return conn, size


def bambu_ftp_candidates(gcode_file: str, subtask_name: str) -> List[str]:
    """Where the running job's .3mf may be on the printer's storage."""
    names: List[str] = []
    gcode_file = (gcode_file or "").strip()
    subtask_name = (subtask_name or "").strip()
    usable = gcode_file and "metadata/" not in gcode_file.lower()   # X1: a path inside the 3mf (RAM disk)
    if usable and gcode_file.lower().endswith(".3mf"):
        if gcode_file.startswith("/"):
            names.append(gcode_file)
        else:
            names.extend(["/" + gcode_file, "/cache/" + gcode_file])
    if subtask_name:
        stem = strip_extension(base_name(subtask_name))
        for folder in ("/", "/cache/"):
            names.extend([folder + stem + ".gcode.3mf", folder + stem + ".3mf"])
    if usable and not gcode_file.lower().endswith(".3mf"):
        stem = base_name(gcode_file)
        for folder in ("/", "/cache/"):
            names.extend([folder + stem + ".3mf", folder + stem + ".gcode.3mf"])
    unique: List[str] = []
    for name in names:
        if name not in unique:
            unique.append(name)
    return unique


def _loose_name(name: str) -> str:
    return re.sub(r"[\s_\-]+", " ", strip_extension(base_name(name))).strip().casefold()


def parse_slice_info(xml_bytes: bytes, plate_index: Optional[int]) -> Optional[Dict[str, Any]]:
    """Slicer totals for the printed plate from Metadata/slice_info.config.

    used_m is in metres and used_g in grams per filament; the plate's "weight" is its total in grams.
    """
    root = ElementTree.fromstring(xml_bytes)
    plates = root.findall("plate")
    plate = None
    if plate_index is not None:
        for candidate in plates:
            for meta in candidate.findall("metadata"):
                if meta.get("key") == "index" and to_int(meta.get("value")) == plate_index:
                    plate = candidate
    elif len(plates) == 1:
        plate = plates[0]
    if plate is None:
        return None
    weight = None
    for meta in plate.findall("metadata"):
        if meta.get("key") == "weight":
            weight = to_float(meta.get("value"))
    grams = 0.0
    metres = 0.0
    found = False
    types: List[str] = []
    for filament in plate.findall("filament"):
        used_g = to_float(filament.get("used_g"))
        used_m = to_float(filament.get("used_m"))
        if used_g is not None:
            grams += used_g
            found = True
        if used_m is not None:
            metres += used_m
            found = True
        if filament.get("type"):
            types.append(filament.get("type") or "")
    if not found and weight is None:
        return None
    return {
        "planned_grams": weight if weight is not None and weight > 0 else (grams if found else None),
        "planned_mm": metres * 1000.0 if metres > 0 else None,
        "material": materials_text(types),
    }


def read_slice_info(fileobj: Any) -> bytes:
    with zipfile.ZipFile(fileobj) as archive:
        for entry in archive.infolist():
            if entry.filename.lower() == "metadata/slice_info.config":
                if entry.file_size > 2 * 1024 * 1024:
                    raise ValueError("slice_info.config beklenenden büyük")
                return archive.read(entry)
    raise KeyError("Metadata/slice_info.config yok")


def _ftp_find(ftp: Any, candidates: List[str], subtask_name: str) -> Optional[str]:
    for path in candidates:
        try:
            ftp.size(path)
            return path
        except ftplib.error_perm as err:
            if str(err)[:3] == "550":
                continue
            return path                       # SIZE not supported: try to download it anyway
    wanted = _loose_name(subtask_name) if subtask_name else ""
    if not wanted:
        return None
    for folder in ("/cache", "/"):
        try:
            names = ftp.nlst(folder)
        except ftplib.all_errors:
            continue
        for name in names[:500]:
            if name.lower().endswith(".3mf") and _loose_name(name) == wanted:
                return name if name.startswith("/") else folder.rstrip("/") + "/" + base_name(name)
    return None


def _ftp_download(ftp: Any, path: str, target: Any, limit: int) -> None:
    ftp.voidcmd("TYPE I")
    conn = ftp.transfercmd("RETR " + path)
    total = 0
    try:
        while True:
            chunk = conn.recv(65536)
            if not chunk:
                break
            total += len(chunk)
            if total > limit:
                raise ValueError("baskı dosyası çok büyük")
            target.write(chunk)
    finally:
        conn.close()                           # no TLS unwrap: some printers never answer it
    ftp.voidresp()


def fetch_bambu_slice_info(host: str, access_code: str, gcode_file: str, subtask_name: str,
                           plate_index: Optional[int], pin: Optional[str] = None,
                           timeout: float = 20.0, limit: int = 300 * 1024 * 1024,
                           ftp_factory: Optional[Callable[[], Any]] = None) -> Optional[Dict[str, Any]]:
    """Reads the running job's .3mf over FTPS and returns the slicer's totals, or None if not found."""
    ftp = ftp_factory() if ftp_factory else ImplicitFTPS(context=printer_tls_context(), timeout=timeout)
    try:
        ftp.connect(host, 990, timeout=timeout)
        if pin:
            seen = certificate_sha256(ftp.sock)
            if seen != pin:
                raise YaziciOkunamadi("yazıcının FTPS sertifikası beklenen parmak iziyle uyuşmuyor")
        ftp.login("bblp", access_code)
        ftp.prot_p()
        path = _ftp_find(ftp, bambu_ftp_candidates(gcode_file, subtask_name), subtask_name)
        if not path:
            return None
        # A real temporary file: zipfile needs seekable(), which SpooledTemporaryFile lacks before 3.11.
        with tempfile.TemporaryFile() as buffer:
            _ftp_download(ftp, path, buffer, limit)
            buffer.seek(0)
            xml_bytes = read_slice_info(buffer)
        result = parse_slice_info(xml_bytes, plate_index)
        if result is not None:
            result["path"] = path
        return result
    finally:
        try:
            ftp.quit()
        except Exception:
            try:
                ftp.close()
            except Exception:
                pass


def _import_paho() -> Any:
    try:
        import paho.mqtt.client as mqtt_client  # imported here: only the Bambu adapter needs it
    except ImportError:
        raise AyarHatasi(
            "Bambu Lab bağlantısı için 'paho-mqtt' paketi gerekli. Kurulum: python3 -m pip install paho-mqtt "
            "(Raspberry Pi OS / Debian: sudo apt install python3-paho-mqtt)")
    return mqtt_client


class BambuAdapter(Adapter):
    kind = "bambu"
    poll_interval = 1.0           # readings are local: the printer pushes its status over MQTT
    network_poll = False
    ready_timeout = 20.0
    PORT = 8883
    PUSHALL_EVERY = 300.0         # OpenBambuAPI: not more often than every 5 minutes (P1P lags)
    QUIET_ASK = 60.0              # no message for this long: ask once for the full status
    SILENCE_LIMIT = 120.0         # still nothing: the link is dead, reconnect

    def __init__(self, host: str, serial: str, access_code: str, use_ftp: bool = False,
                 cert_pin: Optional[str] = None, mqtt_module: Any = None,
                 clock: Callable[[], float] = time.monotonic, wall: Callable[[], float] = time.time,
                 ftp_fetch: Optional[Callable[..., Optional[Dict[str, Any]]]] = None) -> None:
        self.host = host
        self.serial = re.sub(r"\s+", "", serial).upper()
        self.access_code = access_code
        self.use_ftp = use_ftp
        self.pin = re.sub(r"[^0-9a-f]", "", cert_pin.lower()) if cert_pin else None
        self.clock = clock
        self.wall = wall
        self.model = BambuModel()
        self._mqtt = mqtt_module
        self._ftp_fetch = ftp_fetch or fetch_bambu_slice_info
        self._lock = threading.Lock()
        self._client: Any = None
        self._connected = False
        self._ever_connected = False
        self._auth_failed = False
        self._pin_failed = False
        self._fingerprint_logged = False
        self._last_message: Optional[float] = None
        self._last_pushall = -1e9
        self._last_restart = -1e9
        self._sequence = 0
        self._ftp_results: Dict[Tuple[str, str, str], Optional[Dict[str, Any]]] = {}
        self._ftp_attempts: Dict[Tuple[str, str, str], int] = {}
        self._ftp_next_try = 0.0
        self._ftp_thread: Optional[threading.Thread] = None

    @property
    def report_topic(self) -> str:
        return "device/%s/report" % self.serial

    @property
    def request_topic(self) -> str:
        return "device/%s/request" % self.serial

    def describe(self) -> str:
        return "Bambu Lab (%s, seri %s)" % (self.host, self.serial)

    # -- MQTT plumbing -------------------------------------------------------
    def start(self) -> None:
        if self._mqtt is None:
            self._mqtt = _import_paho()
        self._connect()

    def _connect(self) -> None:
        mqtt = self._mqtt
        client_id = "filamentsepeti-" + uuid.uuid4().hex[:10]
        if hasattr(mqtt, "CallbackAPIVersion"):      # paho-mqtt 2.x
            client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=client_id,
                                 protocol=mqtt.MQTTv311, clean_session=True)
        else:                                        # paho-mqtt 1.x
            client = mqtt.Client(client_id=client_id, protocol=mqtt.MQTTv311, clean_session=True)
        client.username_pw_set("bblp", self.access_code)
        client.tls_set_context(printer_tls_context())
        client.tls_insecure_set(True)               # hostname check off for this printer connection only
        client.reconnect_delay_set(min_delay=1, max_delay=60)
        client.on_connect = self._on_connect
        client.on_disconnect = self._on_disconnect
        client.on_message = self._on_message
        client.connect_async(self.host, self.PORT, keepalive=30)
        client.loop_start()
        self._client = client

    def stop(self) -> None:
        client, self._client = self._client, None
        if client is None:
            return
        try:
            client.disconnect()
        except Exception:
            pass
        try:
            client.loop_stop()
        except Exception:
            pass

    def _restart(self) -> None:
        self.stop()
        with self._lock:
            self._connected = False
        self._connect()

    def _on_connect(self, client: Any, userdata: Any, flags: Any, rc: Any, properties: Any = None) -> None:
        code = to_int(getattr(rc, "value", rc))
        if code != 0:
            with self._lock:
                self._auth_failed = code in (4, 5, 134, 135)
            log.debug("Bambu MQTT bağlantısı reddedildi (kod %s)", code)
            return
        fingerprint = certificate_sha256(client.socket()) if hasattr(client, "socket") else None
        if fingerprint and not self._fingerprint_logged:
            log.info("Bambu yazıcının sertifika parmak izi (SHA-256): %s", colon_hex(fingerprint))
            self._fingerprint_logged = True
        if self.pin and fingerprint != self.pin:
            with self._lock:
                self._pin_failed = True
            client.disconnect()
            return
        with self._lock:
            self._connected = True
            self._auth_failed = False
            self._pin_failed = False
            self._last_message = self.clock()
            first = not self._ever_connected
            self._ever_connected = True
        client.subscribe(self.report_topic, qos=0)
        self._pushall(client)
        if first:
            log.info("Bambu yazıcıya bağlanıldı (MQTT, %s).", self.host)
        else:
            log.debug("Bambu yazıcıya yeniden bağlanıldı.")

    def _on_disconnect(self, client: Any, userdata: Any, *args: Any) -> None:
        with self._lock:
            self._connected = False
        log.debug("Bambu MQTT bağlantısı kapandı.")

    def _on_message(self, client: Any, userdata: Any, message: Any) -> None:
        # Runs on paho's network thread: an exception here would stop that thread, so none may escape.
        try:
            payload = getattr(message, "payload", b"")
            if not payload or len(payload) > 1024 * 1024:
                return
            data = json.loads(payload)
            with self._lock:
                self._last_message = self.clock()
                if isinstance(data, dict) and isinstance(data.get("print"), dict):
                    self.model.feed(data["print"], self.wall())
        except Exception as err:
            log.debug("Bambu mesajı işlenemedi: %s", err)

    def _pushall(self, client: Any) -> None:
        self._sequence += 1
        request = {"pushing": {"sequence_id": str(self._sequence), "command": "pushall",
                               "version": 1, "push_target": 1}}
        try:
            client.publish(self.request_topic, json.dumps(request), qos=0)
            self._last_pushall = self.clock()
        except Exception as err:
            log.debug("pushall gönderilemedi: %s", err)

    # -- reading --------------------------------------------------------------
    def read(self) -> Snapshot:
        now = self.clock()
        restart = False
        with self._lock:
            if self._pin_failed:
                raise YaziciOkunamadi("yazıcının sertifikası --bambu-sertifika ile verilen parmak iziyle uyuşmuyor")
            if self._auth_failed:
                raise YaziciYetkiHatasi("Bambu yazıcı erişim kodunu kabul etmedi (erişim kodunu ve seri "
                                        "numarasını kontrol edin)")
            if not self._connected:
                raise YaziciOkunamadi("MQTT bağlantısı kurulamadı (%s:%d)" % (self.host, self.PORT))
            quiet_for = now - self._last_message if self._last_message is not None else 0.0
            silent = quiet_for > self.SILENCE_LIMIT
            if silent and now - self._last_restart > self.SILENCE_LIMIT:
                restart = True
            ask = quiet_for > self.QUIET_ASK and now - self._last_pushall > self.QUIET_ASK
            if self.model.empty:
                raise YaziciOkunamadi("yazıcıdan henüz durum gelmedi")
            key = self.model.job_key()
            gstate = self.model.gstate()
            meta = self._ftp_results.get(key)
            snapshot = self.model.snapshot(self.wall(), meta)
            gcode_file = str(self.model.data.get("gcode_file") or "")
            subtask = str(self.model.data.get("subtask_name") or "")
            plate = self.model.plate_index()
        if silent:
            if restart:
                self._last_restart = now
                log.debug("Bambu yazıcı %d saniyedir veri göndermiyor; yeniden bağlanılıyor.", int(self.SILENCE_LIMIT))
                self._restart()
            raise YaziciOkunamadi("yazıcı bir süredir veri göndermiyor")
        if self._client is not None and (ask or now - self._last_pushall >= self.PUSHALL_EVERY):
            self._pushall(self._client)
        if self.use_ftp and gstate in ("RUNNING", "PAUSE"):
            self._maybe_fetch(key, gcode_file, subtask, plate)
        return snapshot

    def _maybe_fetch(self, key: Tuple[str, str, str], gcode_file: str, subtask: str,
                     plate: Optional[int]) -> None:
        if key in self._ftp_results or not (key[0] or gcode_file):
            return
        if self._ftp_thread is not None and self._ftp_thread.is_alive():
            return
        if self.clock() < self._ftp_next_try:
            return
        attempt = self._ftp_attempts.get(key, 0) + 1
        self._ftp_attempts = {key: attempt}
        if attempt > 3:
            with self._lock:
                self._ftp_results[key] = None
            return
        self._ftp_next_try = self.clock() + 60.0
        self._ftp_thread = threading.Thread(target=self._ftp_worker, name="bambu-ftps", daemon=True,
                                            args=(key, gcode_file, subtask, plate))
        self._ftp_thread.start()

    def _ftp_worker(self, key: Tuple[str, str, str], gcode_file: str, subtask: str,
                    plate: Optional[int]) -> None:
        try:
            result = self._ftp_fetch(self.host, self.access_code, gcode_file, subtask, plate, self.pin)
        except (zipfile.BadZipFile, ElementTree.ParseError, KeyError, ValueError) as err:
            log.warning("Baskı dosyasındaki dilimleyici bilgisi okunamadı: %s", err)
            result = None
        except Exception as err:
            log.warning("Bambu FTPS bağlantısı kurulamadı (%s); bir dakika sonra yeniden denenecek.",
                        describe_error(err))
            return
        with self._lock:
            if len(self._ftp_results) >= 20:
                self._ftp_results.clear()
            self._ftp_results[key] = result
        if result and (result.get("planned_grams") or result.get("planned_mm")):
            log.info("Dilimleyici tahmini okundu (%s): %s g, %s mm", result.get("path"),
                     result.get("planned_grams"), result.get("planned_mm"))
        else:
            log.info("Baskı dosyası yazıcıda bulunamadı ya da tabla bilgisi seçilemedi; planlanan gram "
                     "gönderilmeyecek. Yeni modellerde 'Store Sent Files on External Storage' seçeneğini "
                     "açıp SD kart/USB bellek takın.")


# --- Simulation ---------------------------------------------------------------

class DenemeAdapter(Adapter):
    """Plays a short fake print: idle, printing with rising progress and usage, finished."""

    kind = "deneme"
    network_poll = False

    def __init__(self, steps: int = 12, step_seconds: float = 5.0,
                 wall: Callable[[], float] = time.time) -> None:
        self.steps = steps
        self.poll_interval = step_seconds
        self.wall = wall
        self.tick = 0
        self.done = False
        self.start_ts: Optional[float] = None
        self.planned_grams = 12.6
        self.planned_mm = 4225.0

    def describe(self) -> str:
        return "deneme (sahte baskı)"

    def read(self) -> Snapshot:
        tick = self.tick
        self.tick += 1
        printing = 0 < tick <= self.steps
        trays = [{"slot": "A1", "material": "PLA", "color": "#1A1A1A", "remainPct": 80, "active": tick > 0}]
        temps = {"nozzle": 215.0 if printing else 24.5, "bed": 60.0 if printing else 23.0, "chamber": None}
        if tick == 0:
            return Snapshot("idle", None, trays, temps)
        if self.start_ts is None:
            self.start_ts = float(int(self.wall()))
        fraction = min(tick, self.steps + 1) / (self.steps + 1)
        finished = tick > self.steps
        if finished:
            fraction = 1.0
            self.done = True
        info = JobInfo(
            file_key="deneme_baskisi.gcode", name="Deneme baskısı", start_ts=self.start_ts,
            progress=round(fraction * 100.0, 1),
            elapsed_sec=min(tick, self.steps + 1) * self.poll_interval,
            remaining_sec=0.0 if finished else (self.steps + 1 - tick) * self.poll_interval,
            planned_grams=self.planned_grams, planned_mm=self.planned_mm,
            used_grams=round(self.planned_grams * fraction, 2), used_mm=round(self.planned_mm * fraction, 1),
            material="PLA")
        return Snapshot("finished" if finished else "printing", info, trays, temps)


# ---------------------------------------------------------------------------
# The agent loop
# ---------------------------------------------------------------------------

def _body_key(body: Dict[str, Any]) -> Tuple[str, Optional[str]]:
    job = body.get("job") or {}
    return body.get("state"), job.get("id")


class Agent:
    """Reads the printer, keeps job identity, and sends bodies to the site on schedule."""

    def __init__(self, adapter: Adapter, tracker: JobTracker, site: Any, store: Optional[StateStore] = None,
                 *, once: bool = False, demo: bool = False,
                 clock: Callable[[], float] = time.monotonic, wall: Callable[[], float] = time.time,
                 sleep: Optional[Callable[[float], None]] = None, out: Any = None,
                 stop_event: Optional[threading.Event] = None, max_runtime: Optional[float] = None) -> None:
        self.adapter = adapter
        self.tracker = tracker
        self.site = site
        self.store = store
        self.once = once
        self.demo = demo
        self.clock = clock
        self.wall = wall
        self.stop_event = stop_event or threading.Event()
        self.sleep = sleep or self._wait
        self.out = out or sys.stdout
        self.max_runtime = max_runtime if max_runtime is not None else (600.0 if demo else None)
        self.throttle = LogThrottle(clock)
        self.pending: Deque[Tuple[Dict[str, Any], float]] = collections.deque()
        self.latest: Optional[Dict[str, Any]] = None
        self.last_sent_key: Optional[Tuple[str, Optional[str]]] = None
        self.last_sent_at: Optional[float] = None
        self.blocked_until = 0.0
        self.site_failures = 0
        self.printer_fail_since: Optional[float] = None
        self.printer_failures = 0
        self.printer_seen = False
        self.printer_warned = False
        self.started_at = clock()
        self.next_poll = 0.0
        self.last_save: Optional[float] = None
        self.exit_code = 0
        self._pending_dirty = False

    def stop(self) -> None:
        self.stop_event.set()

    # -- main loop -------------------------------------------------------------
    def run(self) -> int:
        self._restore()
        self.adapter.start()
        started = self.started_at = self.clock()
        try:
            if self.once:
                return self._run_once()
            while not self.stop_event.is_set():
                now = self.clock()
                if now >= self.next_poll:
                    self._poll(now)
                self._send_step(self.clock())
                self._maybe_save()
                if self.exit_code:
                    break
                if self.demo and self._demo_complete():
                    log.info("Deneme tamamlandı: sahte baskı siteye bildirildi.")
                    break
                if self.max_runtime is not None and self.clock() - started > self.max_runtime:
                    log.error("Süre doldu; bildirimlerin hepsi gönderilemedi.")
                    self.exit_code = 1
                    break
                self.sleep(self._time_to_next(self.clock()))
            return self.exit_code
        except KeyboardInterrupt:
            log.info("Durduruluyor (Ctrl+C)…")
            return 0
        finally:
            try:
                self.adapter.stop()
            except Exception as err:
                log.debug("Bağlantı kapatılırken hata: %s", err)
            self._save()

    def _run_once(self) -> int:
        deadline = self.clock() + self.adapter.ready_timeout
        while True:
            try:
                snap = self.adapter.read()
                break
            except YaziciOkunamadi as err:
                if isinstance(err, YaziciYetkiHatasi) or self.clock() >= deadline:
                    log.warning("Yazıcı okunamadı: %s — 'offline' bildirilecek.", err)
                    snap = Snapshot("offline")
                    break
                self.sleep(0.5)
        body = self.tracker.process(snap, self.wall())[-1][0]
        self.out.write(json.dumps(body, ensure_ascii=False, indent=2) + "\n")
        self.out.flush()
        if isinstance(self.site, PrintSite):
            return 0
        problems = contract_problems(body)
        if problems:
            log.error("Gövde sözleşmeye uymuyor (%s); gönderilmedi.", ", ".join(problems))
            return 1
        result = self.site.post(body)
        if result.ok:
            log.info("Gönderildi (HTTP %s).", result.status)
            return 0
        self._report_failure(result, self.clock())
        return 1

    def _poll(self, now: float) -> None:
        snap: Optional[Snapshot]
        try:
            snap = self.adapter.read()
        except YaziciOkunamadi as err:
            snap = self._printer_unreachable(now, err)
            self.next_poll = now + self._retry_delay()
        except Exception as err:
            # An answer we did not expect (or a bug) must not stop the agent: treat it as a failed reading.
            self.throttle.log("bug", logging.ERROR, "Yazıcı okunurken beklenmeyen hata: %s" % err, exc_info=True)
            snap = self._printer_unreachable(now, YaziciOkunamadi("beklenmeyen cevap"))
            self.next_poll = now + self._retry_delay()
        else:
            self._printer_reachable()
            self.next_poll = now + self.adapter.poll_interval
        if snap is None:
            return
        try:
            results = self.tracker.process(snap, self.wall())
        except Exception as err:
            self.throttle.log("bug", logging.ERROR, "Durum işlenirken beklenmeyen hata: %s" % err, exc_info=True)
            return
        for body, must_deliver in results:
            if must_deliver:
                self._queue(body)
        self.latest = results[-1][0]

    def _printer_unreachable(self, now: float, err: YaziciOkunamadi) -> Optional[Snapshot]:
        if self.printer_fail_since is None:
            self.printer_fail_since = now
        self.printer_failures += 1
        # Right after start a push-based adapter is still connecting: no warning for that.
        starting = not self.printer_seen and now - self.started_at < min(self.adapter.ready_timeout, OFFLINE_GRACE)
        if isinstance(err, YaziciYetkiHatasi):
            self.throttle.log("printer", logging.ERROR,
                              "Yazıcı bağlantı bilgilerini reddetti: %s. Ayarlardaki erişim kodunu, parolayı "
                              "ya da API anahtarını kontrol edin." % err)
            self.printer_warned = True
        elif not starting:
            self.throttle.log("printer", logging.WARNING, "Yazıcıya ulaşılamıyor: %s (yeniden denenecek)" % err)
            self.printer_warned = True
        if now - self.printer_fail_since >= OFFLINE_GRACE:
            return Snapshot("offline")
        return None

    def _printer_reachable(self) -> None:
        if self.printer_warned:
            log.info("Yazıcıya yeniden ulaşıldı.")
            self.throttle.forget("printer")
        elif not self.printer_seen:
            log.info("Yazıcı okundu: %s", self.adapter.describe())
        self.printer_seen = True
        self.printer_warned = False
        self.printer_fail_since = None
        self.printer_failures = 0

    def _retry_delay(self) -> float:
        if not self.adapter.network_poll:
            return self.adapter.poll_interval
        return min(30.0, self.adapter.poll_interval * 2 ** min(self.printer_failures - 1, 3))

    def _queue(self, body: Dict[str, Any]) -> None:
        self.pending.append((body, self.wall()))
        while len(self.pending) > PENDING_MAX:
            dropped, _ = self.pending.popleft()
            log.warning("Gönderilemeyen eski bir bitiş bildirimi atıldı: %s", (dropped.get("job") or {}).get("id"))
        self._pending_dirty = True

    # -- sending ---------------------------------------------------------------
    def _send_step(self, now: float) -> None:
        if now < self.blocked_until:
            return
        if self.pending:
            body, queued_at = self.pending[0]
            if self.wall() - queued_at > PENDING_MAX_AGE:
                self.pending.popleft()
                self._pending_dirty = True
                log.warning("İki günden eski bir bitiş bildirimi gönderilemeden atıldı.")
                return
            result = self._post(body, now)
            if result.ok or result.kind in ("bad", "too_big"):
                self.pending.popleft()
                self._pending_dirty = True
                if result.ok:
                    self.last_sent_key = _body_key(body)
                    self.last_sent_at = now
            return
        body = self.latest
        if body is None:
            return
        if self.printer_fail_since is not None and body["state"] != "offline":
            return        # the last reading is stale: wait for the printer or for the offline report
        key = _body_key(body)
        every = SEND_EVERY_ACTIVE if body["state"] in ACTIVE_STATES else SEND_EVERY_IDLE
        if key == self.last_sent_key and self.last_sent_at is not None and now - self.last_sent_at < every:
            return
        result = self._post(body, now)
        if result.ok or result.kind in ("bad", "too_big"):
            self.last_sent_key = key
            self.last_sent_at = now

    def _post(self, body: Dict[str, Any], now: float) -> SendResult:
        self.blocked_until = now + MIN_POST_GAP
        problems = contract_problems(body)
        if problems:
            log.error("Gövde sözleşmeye uymuyor (%s); gönderilmedi.", ", ".join(problems))
            return SendResult(False, "bad", message=", ".join(problems))
        result = self.site.post(body)
        if result.ok:
            if self.site_failures or self.throttle.forget("site"):
                log.info("Siteye yeniden ulaşıldı.")
            self.site_failures = 0
            job = body.get("job") or {}
            log.debug("Gönderildi: %s%s", body["state"],
                      " %%%s" % job.get("progress") if job.get("progress") is not None else "")
            return result
        self._report_failure(result, now)
        return result

    def _report_failure(self, result: SendResult, now: float) -> None:
        kind = result.kind
        if kind == "auth":
            self.blocked_until = now + AUTH_BACKOFF
            self.throttle.log("site", logging.ERROR,
                              "Site bağlantı anahtarını kabul etmedi (401): anahtar geçersiz. Sitedeki Hesabım → "
                              "Yazıcılar → Bağla bölümünden yeni anahtar alıp ayar dosyasına yazın. "
                              "5 dakika sonra yeniden denenecek.")
            if self.demo:
                self.exit_code = 1
        elif kind == "rate":
            wait = max(MIN_POST_GAP, result.retry_after if result.retry_after is not None else 5.0)
            wait = min(wait, 3600.0)
            self.blocked_until = now + wait
            self.throttle.log("site-429", logging.WARNING,
                              "Site çok sık gönderim bildirdi (429); %d saniye bekleniyor." % math.ceil(wait),
                              every=300.0)
        elif kind == "bad":
            self.throttle.log("site-400", logging.ERROR,
                              "Site gövdeyi reddetti (400): %s" % (result.message or "ayrıntı yok"))
        elif kind == "too_big":
            self.throttle.log("site-413", logging.ERROR, "Site gövdeyi çok büyük buldu (413).")
        elif kind in ("not_found", "redirect"):
            self.blocked_until = now + AUTH_BACKOFF
            self.throttle.log("site", logging.ERROR,
                              "Site adresi yanlış görünüyor (HTTP %s%s). Ayarlardaki \"site\" değerini kontrol "
                              "edin; 5 dakika sonra yeniden denenecek."
                              % (result.status, ", " + result.message if result.message else ""))
            if self.demo:
                self.exit_code = 1
        else:
            self.site_failures += 1
            delay = min(60.0, 5.0 * 2 ** min(self.site_failures - 1, 4))
            self.blocked_until = now + delay
            what = result.message or ("HTTP %s" % result.status)
            self.throttle.log("site", logging.WARNING,
                              "Siteye gönderilemedi: %s; %d saniye sonra yeniden denenecek." % (what, delay))

    # -- timing, persistence ---------------------------------------------------
    def _time_to_next(self, now: float) -> float:
        candidates = [self.next_poll]
        if self.pending:
            candidates.append(max(self.blocked_until, now))
        elif self.latest is not None:
            due = self.blocked_until
            if _body_key(self.latest) == self.last_sent_key and self.last_sent_at is not None:
                every = SEND_EVERY_ACTIVE if self.latest["state"] in ACTIVE_STATES else SEND_EVERY_IDLE
                due = max(due, self.last_sent_at + every)
            candidates.append(due)
        return clamp(min(candidates) - now, 0.05, 1.0)

    def _wait(self, seconds: float) -> None:
        # Short slices keep Ctrl+C responsive on Windows too.
        end = time.monotonic() + max(0.0, seconds)
        while not self.stop_event.is_set():
            left = end - time.monotonic()
            if left <= 0:
                return
            self.stop_event.wait(min(0.5, left))

    def _demo_complete(self) -> bool:
        return (bool(getattr(self.adapter, "done", False)) and not self.pending and self.latest is not None
                and self.last_sent_key == _body_key(self.latest))

    def _restore(self) -> None:
        if self.store is None:
            return
        data = self.store.load()
        self.tracker.load(data.get("is"))
        now = self.wall()
        for item in data.get("bekleyen") or []:
            if isinstance(item, dict) and isinstance(item.get("govde"), dict):
                queued_at = to_float(item.get("zaman")) or now
                if now - queued_at <= PENDING_MAX_AGE:
                    body = item["govde"]
                    if body.get("state") in TERMINAL_STATES and isinstance(body.get("job"), dict):
                        body["job"]["seenRunning"] = True     # queued only for prints the agent watched
                    self.pending.append((body, queued_at))
        if self.pending:
            log.info("Önceki çalışmadan gönderilmemiş %d bitiş bildirimi var; gönderilecek.", len(self.pending))
        if self.tracker.job is not None:
            log.debug("Önceki çalışmadan kalan iş: %s", self.tracker.job.id)

    def _maybe_save(self) -> None:
        if self.store is None or self.once:
            return
        now = self.clock()
        periodic = (self.tracker.job is not None and self.tracker.job.state in ACTIVE_STATES
                    and (self.last_save is None or now - self.last_save >= SAVE_EVERY))
        if self.tracker.dirty or self._pending_dirty or periodic:
            self._save()

    def _save(self) -> None:
        if self.store is None or self.once:
            return
        self.store.save({"is": self.tracker.to_json(),
                         "bekleyen": [{"govde": body, "zaman": queued} for body, queued in self.pending]})
        self.tracker.dirty = False
        self._pending_dirty = False
        self.last_save = self.clock()


# ---------------------------------------------------------------------------
# Configuration and command line
# ---------------------------------------------------------------------------

CONFIG_KEYS: Dict[str, type] = {
    "site": str, "anahtar": str, "tur": str, "adres": str, "seri": str, "erisim_kodu": str,
    "kullanici": str, "parola": str, "api_anahtari": str, "bambu_ftp": bool,
    # optional extras
    "durum_dosyasi": str, "gunluk_dosyasi": str, "bambu_sertifika": str,
}
SECRET_KEYS = ("anahtar", "erisim_kodu", "parola", "api_anahtari")


def read_config_file(path: str) -> Dict[str, Any]:
    try:
        with open(path, "r", encoding="utf-8-sig") as handle:    # -sig: files saved by Windows Notepad
            raw = handle.read()
    except OSError as err:
        raise AyarHatasi("Ayar dosyası açılamadı (%s): %s" % (path, err.strerror or err))
    try:
        data = json.loads(raw)
    except ValueError as err:
        raise AyarHatasi("Ayar dosyası geçerli JSON değil (%s): satır %s, sütun %s"
                         % (path, getattr(err, "lineno", "?"), getattr(err, "colno", "?")))
    if not isinstance(data, dict):
        raise AyarHatasi("Ayar dosyası bir JSON nesnesi olmalı: { \"anahtar\": \"…\", … }")
    values: Dict[str, Any] = {}
    for key, value in data.items():
        if key not in CONFIG_KEYS:
            log.warning("Ayar dosyasındaki bilinmeyen alan yok sayıldı: %s", key)
            continue
        if value is None:
            continue
        if CONFIG_KEYS[key] is bool:
            if not isinstance(value, bool):
                raise AyarHatasi("Ayar dosyasında \"%s\" true ya da false olmalı." % key)
            values[key] = value
        else:
            if not isinstance(value, str):
                raise AyarHatasi("Ayar dosyasında \"%s\" tırnak içinde bir metin olmalı." % key)
            values[key] = value.strip()
    if os.name == "posix" and any(values.get(key) for key in SECRET_KEYS):
        try:
            if os.stat(path).st_mode & 0o004:
                log.warning("Ayar dosyasını bilgisayardaki herkes okuyabiliyor; şunu çalıştırın: chmod 600 %s", path)
        except OSError:
            pass
    return values


def build_config(args: argparse.Namespace) -> Dict[str, Any]:
    values: Dict[str, Any] = {"site": VARSAYILAN_SITE, "kullanici": "maker", "bambu_ftp": False}
    if args.ayar:
        values.update(read_config_file(args.ayar))
    if not values.get("anahtar") and os.environ.get("FILAMENTSEPETI_ANAHTAR"):
        values["anahtar"] = os.environ["FILAMENTSEPETI_ANAHTAR"].strip()
    for key in CONFIG_KEYS:
        value = getattr(args, key, None)
        if value is not None:
            values[key] = value.strip() if isinstance(value, str) else value
    return values


def normalize_site(url: str) -> str:
    text = (url or "").strip().rstrip("/")
    parsed = urllib.parse.urlparse(text)
    if parsed.scheme == "https" and parsed.hostname:
        return text
    if parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1", "::1"):
        return text                       # local testing only
    raise AyarHatasi("Site adresi https:// ile başlamalı (örnek: %s)." % VARSAYILAN_SITE)


def validate_config(values: Dict[str, Any], args: argparse.Namespace) -> None:
    for key in SECRET_KEYS:
        register_secret(values.get(key))
    values["site"] = normalize_site(values.get("site") or VARSAYILAN_SITE)
    token = values.get("anahtar") or ""
    if not args.gonderme:
        if not token:
            raise AyarHatasi("Bağlantı anahtarı eksik. Sitede Hesabım → Yazıcılar → Bağla bölümünden alın; "
                             "ayar dosyasında \"anahtar\" alanına ya da --anahtar ile verin.")
        if not ANAHTAR_DESENI.match(token):
            raise AyarHatasi("Bağlantı anahtarı geçersiz: \"fs_\" ile başlayan 46 karakterlik bir anahtar "
                             "bekleniyor (harf, rakam, - ve _). Anahtarı sitedeki Hesabım → Yazıcılar → Bağla "
                             "bölümünden yeniden kopyalayın; başta ya da sonda boşluk kalmamalı.")
    if values.get("bambu_sertifika"):
        pin = re.sub(r"[^0-9a-f]", "", values["bambu_sertifika"].lower())
        if len(pin) != 64:
            raise AyarHatasi("bambu_sertifika 64 onaltılık karakterlik bir SHA-256 parmak izi olmalı.")
        values["bambu_sertifika"] = pin
    if args.deneme:
        return
    kind = (values.get("tur") or "").strip().lower()
    if not kind:
        raise AyarHatasi("Yazıcı türü eksik: --tur bambu | moonraker | prusalink | octoprint "
                         "(ayar dosyasında \"tur\").")
    if kind not in TURLER:
        raise AyarHatasi("Bilinmeyen yazıcı türü: %s (bambu, moonraker, prusalink ya da octoprint olmalı)." % kind)
    values["tur"] = kind
    if not values.get("adres"):
        raise AyarHatasi("Yazıcı adresi eksik: --adres 192.168.1.50 (ayar dosyasında \"adres\").")
    if kind == "bambu":
        if not values.get("seri") or not values.get("erisim_kodu"):
            raise AyarHatasi("Bambu Lab için seri numarası (--seri) ve LAN erişim kodu (--erisim-kodu) gerekli; "
                             "ikisi de yazıcının ekranında, ağ/WLAN ayarlarında görünür.")
    elif kind == "prusalink":
        if not values.get("parola") and not values.get("api_anahtari"):
            raise AyarHatasi("PrusaLink için parola gerekli (--parola). Yazıcının ekranında: Ayarlar → Ağ → "
                             "PrusaLink; kullanıcı adı genellikle 'maker'.")
    elif kind == "octoprint":
        if not values.get("api_anahtari"):
            raise AyarHatasi("OctoPrint için API anahtarı gerekli (--api-anahtari). OctoPrint'te: Ayarlar → "
                             "Uygulama Anahtarları ya da Kullanıcı Ayarları → API anahtarı.")
    if values.get("bambu_ftp") and kind != "bambu":
        log.warning("bambu_ftp yalnızca Bambu Lab yazıcılar için geçerli; yok sayıldı.")


def bambu_host(address: str) -> str:
    text = (address or "").strip()
    if "://" in text:
        text = urllib.parse.urlparse(text).hostname or ""
    text = text.strip("/").strip("[]")
    if not text:
        raise AyarHatasi("Yazıcı adresi anlaşılamadı: %s (örnek: 192.168.1.50)" % address)
    return text


def build_adapter(values: Dict[str, Any], args: argparse.Namespace) -> Adapter:
    if args.deneme:
        adapter = DenemeAdapter()
        if args.bir_kez:
            adapter.tick = adapter.steps // 2       # show a body from the middle of the print
        return adapter
    kind = values["tur"]
    if kind == "bambu":
        return BambuAdapter(bambu_host(values["adres"]), values["seri"], values["erisim_kodu"],
                            use_ftp=bool(values.get("bambu_ftp")), cert_pin=values.get("bambu_sertifika"))
    if kind == "moonraker":
        return MoonrakerAdapter(printer_base_url(values["adres"], 7125), api_key=values.get("api_anahtari"))
    if kind == "prusalink":
        return PrusaLinkAdapter(printer_base_url(values["adres"]), user=values.get("kullanici") or "maker",
                                password=values.get("parola"), api_key=values.get("api_anahtari"))
    return OctoPrintAdapter(printer_base_url(values["adres"]), api_key=values["api_anahtari"])


class _TurkishHelpFormatter(argparse.RawDescriptionHelpFormatter):
    def add_usage(self, usage, actions, groups, prefix=None):  # type: ignore[override]
        return super().add_usage(usage, actions, groups, prefix="kullanım: " if prefix is None else prefix)


_ARGPARSE_TR = (
    ("the following arguments are required", "şu seçenekler gerekli"),
    ("unrecognized arguments", "tanınmayan seçenekler"),
    ("expected one argument", "bir değer bekleniyor"),
    ("invalid choice", "geçersiz seçim"),
    ("choose from", "şunlardan biri olmalı:"),
    ("ignored explicit argument", "fazladan değer yok sayıldı"),
    ("argument ", "seçenek "),
)


class _Parser(argparse.ArgumentParser):
    def error(self, message: str) -> None:  # type: ignore[override]
        for english, turkish in _ARGPARSE_TR:
            message = message.replace(english, turkish)
        self.print_usage(sys.stderr)
        self.exit(2, "%s: hata: %s\n" % (self.prog, message))


EPILOG = """\
örnekler:
  python3 filamentsepeti_ajan.py --ayar ajan.json
  python3 filamentsepeti_ajan.py --ayar ajan.json --bir-kez --gonderme
  python3 filamentsepeti_ajan.py --anahtar fs_... --tur moonraker --adres 192.168.1.50
  python3 filamentsepeti_ajan.py --anahtar fs_... --deneme

Ayar dosyası (ajan.json) örneği:
  {"anahtar": "fs_...", "tur": "bambu", "adres": "192.168.1.20",
   "seri": "01P00A000000000", "erisim_kodu": "12345678", "bambu_ftp": true}

Komut satırındaki değerler ayar dosyasındakileri ezer. Bağlantı anahtarı günlüklerde
gösterilmez. Ayrıntılar: BENIOKU.md
"""


def build_parser() -> argparse.ArgumentParser:
    parser = _Parser(
        prog="filamentsepeti_ajan.py", add_help=False, formatter_class=_TurkishHelpFormatter, epilog=EPILOG,
        description="filamentsepeti.app yazıcı bağlantı ajanı: ev ağınızdaki 3D yazıcının durumunu okur ve "
                    "siteye gönderir (baskı sürerken 5 saniyede, diğer zamanlarda 30 saniyede bir).")
    general = parser.add_argument_group("genel")
    general.add_argument("-h", "--yardim", action="help", help="bu yardımı gösterir ve çıkar")
    general.add_argument("--ayar", metavar="DOSYA", help="JSON ayar dosyası (ör. ajan.json)")
    general.add_argument("--site", metavar="URL", help="site adresi (varsayılan: %s)" % VARSAYILAN_SITE)
    general.add_argument("--anahtar", metavar="ANAHTAR",
                         help="yazıcının bağlantı anahtarı (fs_…; Hesabım → Yazıcılar → Bağla). Komut satırı "
                              "başka kullanıcılara görünebilir; ayar dosyası önerilir")
    printer = parser.add_argument_group("yazıcı")
    printer.add_argument("--tur", type=str.lower, choices=TURLER, help="yazıcı türü")
    printer.add_argument("--adres", metavar="ADRES",
                         help="yazıcının IP adresi ya da adı; Moonraker/OctoPrint/PrusaLink için tam URL de "
                              "olabilir (ör. http://192.168.1.50:7125)")
    printer.add_argument("--seri", metavar="SERİ", help="Bambu Lab: yazıcının seri numarası")
    printer.add_argument("--erisim-kodu", dest="erisim_kodu", metavar="KOD",
                         help="Bambu Lab: LAN erişim kodu (Access Code)")
    printer.add_argument("--kullanici", metavar="AD", help="PrusaLink kullanıcı adı (varsayılan: maker)")
    printer.add_argument("--parola", metavar="PAROLA", help="PrusaLink parolası")
    printer.add_argument("--api-anahtari", dest="api_anahtari", metavar="ANAHTAR",
                         help="OctoPrint ya da Moonraker API anahtarı (X-Api-Key)")
    printer.add_argument("--bambu-ftp", dest="bambu_ftp", action="store_const", const=True, default=None,
                         help="Bambu Lab: baskı dosyasını FTPS ile okuyup dilimleyicinin gram/uzunluk "
                              "tahminini de gönder")
    printer.add_argument("--bambu-sertifika", dest="bambu_sertifika", metavar="SHA256",
                         help="Bambu Lab: yazıcı sertifikasının SHA-256 parmak izi; verilirse başka sertifikayla "
                              "bağlanılmaz (isteğe bağlı)")
    mode = parser.add_argument_group("çalışma biçimi")
    mode.add_argument("--deneme", action="store_true",
                      help="yazıcı olmadan kısa bir sahte baskıyı siteye gönderir (boşta → baskı → bitti)")
    mode.add_argument("--bir-kez", dest="bir_kez", action="store_true",
                      help="bir kez okur, gönderilecek gövdeyi yazdırır, gönderir ve çıkar")
    mode.add_argument("--gonderme", action="store_true",
                      help="siteye göndermez, gövdeleri ekrana yazdırır (anahtar gerekmez)")
    mode.add_argument("--durum-dosyasi", dest="durum_dosyasi", metavar="DOSYA",
                      help="iş kimliklerinin ve gönderilemeyen bitiş bildirimlerinin saklandığı dosya")
    mode.add_argument("--gunluk-dosyasi", dest="gunluk_dosyasi", metavar="DOSYA",
                      help="günlüğü ayrıca bu dosyaya da yaz (1 MB'ta döner)")
    mode.add_argument("-v", "--ayrintili", action="store_true", help="ayrıntılı günlük")
    mode.add_argument("--surum", action="version", version="%(prog)s " + SURUM, help="sürümü gösterir")
    return parser


def _prepare_stdio() -> None:
    for stream in (sys.stdout, sys.stderr):
        if stream is None:
            continue
        try:
            stream.reconfigure(errors="replace")  # type: ignore[attr-defined]
        except (AttributeError, ValueError):
            pass


def _install_signal_handlers(agent: Agent) -> None:
    def handler(signum: int, frame: Any) -> None:
        log.info("Durdurma isteği alındı; kapanıyor…")
        agent.stop()

    if hasattr(signal, "SIGTERM"):
        try:
            signal.signal(signal.SIGTERM, handler)
        except (ValueError, OSError):
            pass        # not in the main thread


def main(argv: Optional[List[str]] = None) -> int:
    _prepare_stdio()
    args = build_parser().parse_args(argv)
    setup_logging(args.ayrintili)
    try:
        values = build_config(args)
        validate_config(values, args)
        if values.get("gunluk_dosyasi"):
            setup_logging(args.ayrintili, values["gunluk_dosyasi"])
        adapter = build_adapter(values, args)
        if args.deneme:
            signature = "deneme"
        else:
            signature = "|".join([values["tur"], values.get("adres") or "", (values.get("seri") or "").upper()])
        state_path = None if args.deneme else (values.get("durum_dosyasi") or default_state_path(signature))
        store = StateStore(state_path, signature, readonly=args.bir_kez)
        site = PrintSite(sys.stdout) if args.gonderme else SiteClient(values["site"], values["anahtar"])
        tracker = JobTracker(adapter.kind, final_state=adapter.final_state)
        agent = Agent(adapter, tracker, site, store, once=args.bir_kez, demo=args.deneme)
        _install_signal_handlers(agent)
        if not args.bir_kez:
            log.info("filamentsepeti ajanı %s başladı: %s → %s", SURUM, adapter.describe(),
                     "yalnızca ekrana yazdırılıyor" if args.gonderme else values["site"])
        code = agent.run()
        if not args.bir_kez:
            log.info("Ajan durdu.")
        return code
    except AyarHatasi as err:
        log.error("%s", err)
        return 2
    except KeyboardInterrupt:
        return 0


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