from __future__ import annotations

import hashlib
import json
import os
import re
import tempfile
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any

from .exceptions import InputValidationError, ProviderDataError

_SECRET_KEYS = re.compile(
    r"password|passwd|pwd|token|secret|authorization|cookie|session|api[_-]?key|otp|captcha",
    re.IGNORECASE,
)


def canonical_json(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))


def atomic_write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
    try:
        with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
            handle.write(text)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(tmp_name, path)
    except Exception:
        try:
            os.unlink(tmp_name)
        except OSError:
            pass
        raise


def atomic_write_json(path: Path, value: Any) -> None:
    atomic_write_text(path, json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n")


def sanitize(value: Any) -> Any:
    if isinstance(value, dict):
        clean = {}
        for key, item in value.items():
            if _SECRET_KEYS.search(str(key)):
                clean[str(key)] = "[REDACTED]"
            else:
                clean[str(key)] = sanitize(item)
        return clean
    if isinstance(value, list):
        return [sanitize(item) for item in value]
    return value



def redact_text(text: Any, secret_values: list[str]) -> str:
    result = str(text or "")
    for secret in sorted({str(value) for value in secret_values if str(value)}, key=len, reverse=True):
        result = result.replace(secret, "[REDACTED]")
    return result

def sha256_bytes(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


def sha256_text(value: str) -> str:
    return sha256_bytes(value.encode("utf-8"))


def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        while True:
            chunk = handle.read(chunk_size)
            if not chunk:
                break
            digest.update(chunk)
    return digest.hexdigest()


def parse_aware_datetime(value: Any, label: str) -> datetime:
    text = str(value or "").strip()
    if not text:
        raise InputValidationError(f"{label} is required")
    if text.endswith("Z"):
        text = text[:-1] + "+00:00"
    try:
        result = datetime.fromisoformat(text)
    except ValueError as exc:
        raise InputValidationError(f"{label} must be ISO-8601 with timezone") from exc
    if result.tzinfo is None or result.utcoffset() is None:
        raise InputValidationError(f"{label} must include timezone")
    return result


def utc_iso(value: datetime) -> str:
    return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")


def decimal_string(value: Any, label: str, nullable: bool = True) -> str | None:
    if value is None or str(value).strip() == "":
        if nullable:
            return None
        raise ProviderDataError(f"{label} is required")
    try:
        number = Decimal(str(value).strip())
    except (InvalidOperation, ValueError) as exc:
        raise ProviderDataError(f"{label} must be a decimal value") from exc
    if not number.is_finite():
        raise ProviderDataError(f"{label} must be finite")
    return format(number, "f")


def safe_key(value: Any, label: str = "key") -> str:
    text = str(value or "").strip().lower()
    if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]{0,127}", text):
        raise InputValidationError(f"{label} contains unsupported characters")
    return text


def safe_job_id(value: Any) -> str:
    text = str(value or "").strip()
    if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,190}", text):
        raise InputValidationError("job_id contains unsupported characters")
    return text


def ensure_within(root: Path, candidate: Path) -> Path:
    root_resolved = root.resolve()
    candidate_resolved = candidate.resolve()
    if root_resolved != candidate_resolved and root_resolved not in candidate_resolved.parents:
        raise InputValidationError("path escapes configured storage root")
    return candidate_resolved
