from __future__ import annotations

import base64
from dataclasses import dataclass


class ImageCaptchaError(RuntimeError):
    pass


@dataclass(frozen=True)
class ImageCaptchaSolver:
    mode: str = "ddddocr"

    def solve(self, image_bytes: bytes) -> str:
        if self.mode in ("off", "none", ""):
            raise ImageCaptchaError("Image captcha solver is disabled")

        if self.mode != "ddddocr":
            raise ImageCaptchaError(f"Unsupported image captcha mode: {self.mode}")

        try:
            import ddddocr
        except ImportError as exc:
            raise ImageCaptchaError("ddddocr is not installed. Run: pip install -r requirements.txt") from exc

        ocr = ddddocr.DdddOcr(show_ad=False)
        result = ocr.classification(image_bytes)
        code = "".join(ch for ch in result.strip() if ch.isalnum())
        if not code:
            raise ImageCaptchaError(f"Failed to recognize image captcha, raw result: {result!r}")
        return code


def decode_data_image(src: str) -> bytes:
    if not src.startswith("data:image"):
        raise ImageCaptchaError("Captcha image is not a data URL")
    _, payload = src.split(",", 1)
    return base64.b64decode(payload)
