"""Offline trust/signature utilities for trusted .osmoimg artifacts."""

from __future__ import annotations

import base64
import hashlib
import json
import os
import urllib.error
import urllib.request
import zipfile
from datetime import datetime, timezone
from io import BytesIO
from pathlib import Path
from typing import Any, Dict, List, Optional


TRUST_SCHEMA_VERSION = "1"
TRUST_SIGNATURE_ALGORITHM = "ed25519"
DEFAULT_SIGNER_ID = "default"
DEFAULT_SIGNER_BACKEND = "local-keyring"
KMS_SIGNER_BACKEND = "aws-kms"
SUPPORTED_SIGNER_BACKENDS = {DEFAULT_SIGNER_BACKEND, KMS_SIGNER_BACKEND}
TRANSPARENCY_SCHEMA_VERSION = "1"
_FALLBACK_TRUST_HOME: Optional[Path] = None


class TrustDependencyError(RuntimeError):
    """Raised when trust crypto dependencies are missing."""


def _load_crypto():
    try:
        from cryptography.hazmat.primitives import serialization
        from cryptography.hazmat.primitives.asymmetric.ed25519 import (
            Ed25519PrivateKey,
            Ed25519PublicKey,
        )
    except ImportError as exc:
        raise TrustDependencyError(
            "Trusted .osmoimg signing requires cryptography. "
            "Install with: pip install cryptography"
        ) from exc
    return Ed25519PrivateKey, Ed25519PublicKey, serialization


def _utc_now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def _sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def _safe_id(value: str) -> str:
    cleaned = "".join(ch for ch in str(value) if ch.isalnum() or ch in ("-", "_", "."))
    cleaned = cleaned.strip(".")
    if not cleaned:
        raise ValueError("Signer name cannot be empty")
    return cleaned


def trust_home() -> Path:
    global _FALLBACK_TRUST_HOME
    override = os.environ.get("OSMOSIS_TRUST_HOME", "").strip()
    if override:
        return Path(override)
    if _FALLBACK_TRUST_HOME is not None:
        return _FALLBACK_TRUST_HOME

    primary = Path.home() / ".model_osmosis" / "trust"
    try:
        primary.mkdir(parents=True, exist_ok=True)
        return primary
    except Exception:
        fallback = Path.cwd() / ".model_osmosis" / "trust"
        fallback.mkdir(parents=True, exist_ok=True)
        _FALLBACK_TRUST_HOME = fallback
        return fallback


def _keys_dir() -> Path:
    return trust_home() / "keys"


def _trusted_dir() -> Path:
    return trust_home() / "trusted"


def _private_key_path(signer_id: str) -> Path:
    return _keys_dir() / f"{_safe_id(signer_id)}.ed25519.pem"


def _public_key_path(signer_id: str) -> Path:
    return _keys_dir() / f"{_safe_id(signer_id)}.ed25519.pub"


def _trusted_key_path(signer_id: str) -> Path:
    return _trusted_dir() / f"{_safe_id(signer_id)}.ed25519.pub"


def _ensure_dirs() -> None:
    _keys_dir().mkdir(parents=True, exist_ok=True)
    _trusted_dir().mkdir(parents=True, exist_ok=True)


def _transparency_dir() -> Path:
    return trust_home() / "transparency"


def _transparency_log_path() -> Path:
    return _transparency_dir() / "events.jsonl"


def _audit_dir() -> Path:
    return trust_home() / "audit"


def _audit_log_path() -> Path:
    return _audit_dir() / "events.jsonl"


def _public_key_bytes(public_key: Any) -> bytes:
    _, _, serialization = _load_crypto()
    return public_key.public_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PublicFormat.Raw,
    )


def _key_id(public_key_raw: bytes) -> str:
    return _sha256(public_key_raw)[:16]


def _decode_public_key_file(raw: bytes) -> bytes:
    Ed25519PrivateKey, Ed25519PublicKey, serialization = _load_crypto()
    data = raw.strip()
    if not data:
        raise ValueError("Public key file is empty")

    # Raw key bytes.
    if len(data) == 32:
        return bytes(data)

    # PEM public key.
    if b"BEGIN PUBLIC KEY" in data:
        pub = serialization.load_pem_public_key(data)
        if not isinstance(pub, Ed25519PublicKey):
            raise ValueError("Public key is not Ed25519")
        return _public_key_bytes(pub)

    # Base64 text.
    try:
        decoded = base64.b64decode(data, validate=True)
        if len(decoded) == 32:
            return decoded
    except Exception:
        pass

    raise ValueError("Unsupported public key format")


def ensure_default_signer() -> Dict[str, str]:
    return generate_signer(DEFAULT_SIGNER_ID, overwrite=False)


def generate_signer(name: str, *, overwrite: bool = False) -> Dict[str, str]:
    signer_id = _safe_id(name)
    Ed25519PrivateKey, _, serialization = _load_crypto()
    _ensure_dirs()

    priv_path = _private_key_path(signer_id)
    pub_path = _public_key_path(signer_id)
    trusted_path = _trusted_key_path(signer_id)

    if priv_path.exists() and not overwrite:
        public_raw = _decode_public_key_file(pub_path.read_bytes()) if pub_path.exists() else b""
        return {
            "signer_id": signer_id,
            "key_id": _key_id(public_raw) if public_raw else "",
            "private_key_path": str(priv_path),
            "public_key_path": str(pub_path),
            "trusted_key_path": str(trusted_path if trusted_path.exists() else ""),
            "created": "false",
        }

    private_key = Ed25519PrivateKey.generate()
    public_key = private_key.public_key()
    public_raw = _public_key_bytes(public_key)

    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
    priv_path.write_bytes(private_pem)
    pub_path.write_text(base64.b64encode(public_raw).decode("ascii"), encoding="utf-8")
    trusted_path.write_text(base64.b64encode(public_raw).decode("ascii"), encoding="utf-8")

    return {
        "signer_id": signer_id,
        "key_id": _key_id(public_raw),
        "private_key_path": str(priv_path),
        "public_key_path": str(pub_path),
        "trusted_key_path": str(trusted_path),
        "created": "true",
    }


def list_keys() -> Dict[str, List[Dict[str, str]]]:
    _ensure_dirs()
    private_entries: List[Dict[str, str]] = []
    trusted_entries: List[Dict[str, str]] = []

    for priv in sorted(_keys_dir().glob("*.ed25519.pem")):
        signer_id = priv.stem.replace(".ed25519", "")
        key_id = ""
        pub = _public_key_path(signer_id)
        if pub.exists():
            try:
                key_id = _key_id(_decode_public_key_file(pub.read_bytes()))
            except Exception:
                key_id = "invalid"
        private_entries.append(
            {
                "signer_id": signer_id,
                "key_id": key_id,
                "private_key_path": str(priv),
                "public_key_path": str(pub) if pub.exists() else "",
            }
        )

    for trusted in sorted(_trusted_dir().glob("*.ed25519.pub")):
        signer_id = trusted.stem.replace(".ed25519", "")
        key_id = ""
        try:
            key_id = _key_id(_decode_public_key_file(trusted.read_bytes()))
        except Exception:
            key_id = "invalid"
        trusted_entries.append(
            {
                "signer_id": signer_id,
                "key_id": key_id,
                "trusted_key_path": str(trusted),
            }
        )

    return {"private_keys": private_entries, "trusted_signers": trusted_entries}


def import_trusted_signer(name: str, pubkey_file: str | Path) -> Dict[str, str]:
    signer_id = _safe_id(name)
    _ensure_dirs()
    source = Path(pubkey_file)
    if not source.exists():
        raise FileNotFoundError(f"Public key file not found: {source}")

    public_raw = _decode_public_key_file(source.read_bytes())
    target = _trusted_key_path(signer_id)
    target.write_text(base64.b64encode(public_raw).decode("ascii"), encoding="utf-8")
    return {
        "signer_id": signer_id,
        "key_id": _key_id(public_raw),
        "trusted_key_path": str(target),
    }


def revoke_trusted_signer(name: str) -> bool:
    signer_id = _safe_id(name)
    target = _trusted_key_path(signer_id)
    if target.exists():
        target.unlink()
        return True
    return False


def _load_private_key(name: str) -> tuple[Any, bytes]:
    signer_id = _safe_id(name)
    Ed25519PrivateKey, _, serialization = _load_crypto()
    priv_path = _private_key_path(signer_id)
    if not priv_path.exists():
        raise FileNotFoundError(
            f"Signer private key not found for '{signer_id}'. "
            f"Create with: osmosis trust keygen --name {signer_id}"
        )
    private_key = serialization.load_pem_private_key(priv_path.read_bytes(), password=None)
    public_raw = _public_key_bytes(private_key.public_key())
    return private_key, public_raw


def load_trusted_public_key(name: str) -> Optional[bytes]:
    signer_id = _safe_id(name)
    target = _trusted_key_path(signer_id)
    if not target.exists():
        return None
    return _decode_public_key_file(target.read_bytes())


def canonical_statement_bytes(statement: Dict[str, Any]) -> bytes:
    return json.dumps(statement, sort_keys=True, separators=(",", ":")).encode("utf-8")


def sign_statement(
    statement: Dict[str, Any],
    *,
    signer_id: str,
    ensure_signer: bool = True,
) -> Dict[str, Any]:
    if ensure_signer and not _private_key_path(signer_id).exists():
        generate_signer(signer_id, overwrite=False)
    private_key, public_raw = _load_private_key(signer_id)

    payload = canonical_statement_bytes(statement)
    signature = private_key.sign(payload)
    return {
        "schema_version": TRUST_SCHEMA_VERSION,
        "signer_id": _safe_id(signer_id),
        "key_id": _key_id(public_raw),
        "alg": TRUST_SIGNATURE_ALGORITHM,
        "public_key_b64": base64.b64encode(public_raw).decode("ascii"),
        "signature_b64": base64.b64encode(signature).decode("ascii"),
        "statement": statement,
    }


def verify_trust_block(
    trust_block: Dict[str, Any],
    *,
    payload_bytes: bytes,
    require_trust: bool = False,
) -> Dict[str, Any]:
    status = "unsigned"
    signer_id = str(trust_block.get("signer_id", "")).strip() if isinstance(trust_block, dict) else ""
    verified_at = _utc_now()
    payload_sha = _sha256(payload_bytes)

    result: Dict[str, Any] = {
        "trust_status": "unsigned",
        "signer_id": signer_id or None,
        "key_id": str(trust_block.get("key_id", "")) if isinstance(trust_block, dict) else None,
        "signature_alg": str(trust_block.get("alg", "")) if isinstance(trust_block, dict) else None,
        "payload_sha256": payload_sha,
        "verified_at": verified_at,
        "reason": "",
    }

    if not isinstance(trust_block, dict) or not trust_block:
        result["reason"] = "No trust signature found in artifact header"
        if require_trust:
            result["reason"] += "; trusted artifact required"
        return result

    if str(trust_block.get("alg")) != TRUST_SIGNATURE_ALGORITHM:
        result["trust_status"] = "tampered"
        result["reason"] = f"Unsupported signature algorithm: {trust_block.get('alg')}"
        return result

    statement = trust_block.get("statement")
    signature_b64 = str(trust_block.get("signature_b64", ""))
    public_key_b64 = str(trust_block.get("public_key_b64", ""))
    if not isinstance(statement, dict) or not signature_b64 or not public_key_b64:
        result["trust_status"] = "tampered"
        result["reason"] = "Malformed trust block"
        return result

    stated_payload_sha = str(statement.get("payload_sha256", ""))
    if stated_payload_sha != payload_sha:
        result["trust_status"] = "tampered"
        result["reason"] = "Payload digest mismatch"
        return result

    try:
        _, Ed25519PublicKey, _ = _load_crypto()
        signature = base64.b64decode(signature_b64)
        public_raw = base64.b64decode(public_key_b64)
        pub = Ed25519PublicKey.from_public_bytes(public_raw)
        pub.verify(signature, canonical_statement_bytes(statement))
    except Exception as exc:
        result["trust_status"] = "tampered"
        result["reason"] = f"Signature verification failed: {exc}"
        return result

    trusted_raw = load_trusted_public_key(signer_id) if signer_id else None
    if trusted_raw is not None:
        if trusted_raw != public_raw:
            result["trust_status"] = "tampered"
            result["reason"] = "Trusted key mismatch for signer"
            return result
        status = "trusted"
        reason = "Signature valid and signer trusted"
    else:
        status = "signed_untrusted"
        reason = "Signature valid but signer is not in local trust store"

    result.update(
        {
            "trust_status": status,
            "key_id": _key_id(public_raw),
            "signature_alg": TRUST_SIGNATURE_ALGORITHM,
            "payload_sha256": payload_sha,
            "reason": reason,
        }
    )
    return result


def deterministic_zip_bytes(payload: bytes) -> bytes:
    """
    Canonicalize zip bytes for strict reproducibility.

    Rewrites entries in sorted order with a fixed DOS timestamp.
    """
    try:
        source = zipfile.ZipFile(BytesIO(payload), "r")
    except zipfile.BadZipFile:
        return payload

    with source:
        entries = []
        for info in source.infolist():
            entries.append((info, source.read(info.filename)))

    buffer = BytesIO()
    with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as out:
        for info, data in sorted(entries, key=lambda item: item[0].filename):
            normalized = zipfile.ZipInfo(filename=info.filename, date_time=(1980, 1, 1, 0, 0, 0))
            normalized.compress_type = info.compress_type
            normalized.external_attr = info.external_attr
            normalized.comment = b""
            normalized.extra = b""
            out.writestr(normalized, data)
    return buffer.getvalue()


class SignerBackend:
    """Base signer backend interface for future KMS integrations."""

    backend_name = "base"

    def sign_statement(self, statement: Dict[str, Any], signer_id: str) -> Dict[str, Any]:
        raise NotImplementedError

    def verify(self, trust_block: Dict[str, Any], payload_bytes: bytes) -> Dict[str, Any]:
        raise NotImplementedError


class LocalSignerBackend(SignerBackend):
    """Default local filesystem signer backend."""

    backend_name = DEFAULT_SIGNER_BACKEND

    def sign_statement(self, statement: Dict[str, Any], signer_id: str) -> Dict[str, Any]:
        block = sign_statement(statement, signer_id=signer_id, ensure_signer=True)
        block["backend"] = self.backend_name
        return block

    def verify(self, trust_block: Dict[str, Any], payload_bytes: bytes) -> Dict[str, Any]:
        result = verify_trust_block(trust_block, payload_bytes=payload_bytes, require_trust=False)
        result["signer_backend"] = self.backend_name
        return result


class AWSSignerBackend(SignerBackend):
    """
    Simulated KMS-backed signer.

    Uses local Ed25519 keys for offline compatibility while stamping backend
    metadata that can be routed to real KMS implementations later.
    """

    backend_name = KMS_SIGNER_BACKEND

    def __init__(self, key_ref: str = "alias/model-osmosis") -> None:
        self.provider = "aws-kms"
        self.key_ref = key_ref

    def sign_statement(self, statement: Dict[str, Any], signer_id: str) -> Dict[str, Any]:
        block = sign_statement(statement, signer_id=signer_id, ensure_signer=True)
        block["backend"] = self.backend_name
        block["kms"] = {
            "provider": self.provider,
            "key_ref": self.key_ref,
            "mode": "envelope-simulated",
        }
        return block

    def verify(self, trust_block: Dict[str, Any], payload_bytes: bytes) -> Dict[str, Any]:
        result = verify_trust_block(trust_block, payload_bytes=payload_bytes, require_trust=False)
        result["signer_backend"] = self.backend_name
        kms_block = trust_block.get("kms")
        if isinstance(kms_block, dict):
            result["kms_provider"] = kms_block.get("provider")
            result["kms_key_ref"] = kms_block.get("key_ref")
        return result


def _normalize_backend_name(backend_name: Optional[str]) -> str:
    requested = (backend_name or os.environ.get("OSMOSIS_SIGNER_BACKEND", DEFAULT_SIGNER_BACKEND)).strip().lower()
    if requested in {"local", "local-keyring"}:
        return DEFAULT_SIGNER_BACKEND
    if requested in {"kms", "aws-kms", "kms-envelope"}:
        return KMS_SIGNER_BACKEND
    raise ValueError(
        f"Unsupported signer backend '{requested}'. "
        f"Expected one of: {sorted(SUPPORTED_SIGNER_BACKENDS)}"
    )


def get_signer_backend(backend_name: Optional[str] = None) -> SignerBackend:
    normalized = _normalize_backend_name(backend_name)
    if normalized == DEFAULT_SIGNER_BACKEND:
        return LocalSignerBackend()
    if normalized == KMS_SIGNER_BACKEND:
        key_ref = (
            os.environ.get("OSMOSIS_AWS_KMS_KEY_ID", "").strip()
            or os.environ.get("OSMOSIS_KMS_KEY_REF", "").strip()
            or "alias/model-osmosis"
        )
        return AWSSignerBackend(key_ref=key_ref)
    return LocalSignerBackend()


def sign_statement_with_backend(
    statement: Dict[str, Any],
    *,
    signer_id: str,
    backend_name: Optional[str] = None,
) -> Dict[str, Any]:
    backend = get_signer_backend(backend_name)
    block = backend.sign_statement(statement, signer_id=signer_id)
    block.setdefault("backend", backend.backend_name)
    return block


def _transparency_event(
    trust_block: Dict[str, Any],
    *,
    payload_sha256: str,
    artifact_path: Optional[str] = None,
) -> Dict[str, Any]:
    statement = trust_block.get("statement", {}) if isinstance(trust_block, dict) else {}
    statement_sha = ""
    if isinstance(statement, dict):
        statement_sha = _sha256(canonical_statement_bytes(statement))
    return {
        "schema_version": TRANSPARENCY_SCHEMA_VERSION,
        "event_type": "artifact-signature",
        "published_at": _utc_now(),
        "payload_sha256": payload_sha256,
        "signer_id": trust_block.get("signer_id"),
        "key_id": trust_block.get("key_id"),
        "signature_alg": trust_block.get("alg"),
        "signer_backend": trust_block.get("backend", DEFAULT_SIGNER_BACKEND),
        "statement_sha256": statement_sha,
        "tool_version": statement.get("tool_version") if isinstance(statement, dict) else None,
        "artifact_path": artifact_path,
    }


def publish_transparency_event(
    trust_block: Dict[str, Any],
    *,
    payload_sha256: str,
    artifact_path: Optional[str] = None,
) -> Dict[str, Any]:
    """
    Publish trust evidence to a local transparency log and optional HTTP endpoint.

    Always best-effort: returns structured status and never raises.
    """
    result: Dict[str, Any] = {
        "status": "disabled",
        "local_logged": False,
        "remote_logged": False,
        "reason": "",
    }
    if str(os.environ.get("OSMOSIS_TRANSPARENCY_DISABLE", "0")).strip().lower() in {"1", "true", "yes", "on"}:
        result["reason"] = "Transparency logging disabled by OSMOSIS_TRANSPARENCY_DISABLE"
        return result

    event = _transparency_event(
        trust_block,
        payload_sha256=payload_sha256,
        artifact_path=artifact_path,
    )
    try:
        _transparency_dir().mkdir(parents=True, exist_ok=True)
        with _transparency_log_path().open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(event, sort_keys=True, separators=(",", ":")) + "\n")
        result["local_logged"] = True
    except Exception as exc:
        result["reason"] = f"Local transparency log write failed: {exc}"

    endpoint = os.environ.get("OSMOSIS_TRANSPARENCY_URL", "").strip()
    if endpoint:
        timeout_raw = os.environ.get("OSMOSIS_TRANSPARENCY_TIMEOUT_SEC", "2.0").strip()
        try:
            timeout_sec = float(timeout_raw)
        except Exception:
            timeout_sec = 2.0
        try:
            req = urllib.request.Request(
                endpoint,
                method="POST",
                headers={"Content-Type": "application/json"},
                data=json.dumps(event, sort_keys=True, separators=(",", ":")).encode("utf-8"),
            )
            with urllib.request.urlopen(req, timeout=timeout_sec):  # nosec B310
                pass
            result["remote_logged"] = True
        except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
            result["reason"] = (
                f"{result['reason']} | " if result["reason"] else ""
            ) + f"Remote transparency publish failed: {exc}"

    if result["local_logged"] and (not endpoint or result["remote_logged"]):
        result["status"] = "published"
    elif result["local_logged"]:
        result["status"] = "local_only"
    else:
        result["status"] = "failed"
        if not result["reason"]:
            result["reason"] = "Transparency publish failed"
    return result


def verify_transparency_event(
    trust_block: Dict[str, Any],
    *,
    payload_sha256: str,
) -> Dict[str, Any]:
    """
    Verify if this payload/signer tuple exists in the local transparency log.

    Best-effort and non-blocking.
    """
    result: Dict[str, Any] = {
        "status": "not_checked",
        "present_in_local_log": False,
        "reason": "",
    }
    if str(os.environ.get("OSMOSIS_TRANSPARENCY_DISABLE", "0")).strip().lower() in {"1", "true", "yes", "on"}:
        result["status"] = "disabled"
        result["reason"] = "Transparency verification disabled"
        return result

    log_path = _transparency_log_path()
    if not log_path.exists():
        result["status"] = "local_missing"
        result["reason"] = "No local transparency log found"
        return result

    signer_id = trust_block.get("signer_id")
    key_id = trust_block.get("key_id")
    try:
        with log_path.open("r", encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if not line:
                    continue
                try:
                    item = json.loads(line)
                except Exception:
                    continue
                if (
                    item.get("payload_sha256") == payload_sha256
                    and item.get("signer_id") == signer_id
                    and item.get("key_id") == key_id
                ):
                    result["status"] = "local_found"
                    result["present_in_local_log"] = True
                    return result
    except Exception as exc:
        result["status"] = "error"
        result["reason"] = f"Transparency verification failed: {exc}"
        return result

    result["status"] = "local_not_found"
    result["reason"] = "No matching transparency event in local log"
    return result


def append_audit_event(
    *,
    action: str,
    image_path: str,
    trust_result: Dict[str, Any],
    policy_result: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Append an audit record for trust-sensitive actions.

    Returns a small result dict and never raises.
    """
    event = {
        "schema_version": "1",
        "event_type": "trust-action",
        "occurred_at": _utc_now(),
        "action": action,
        "image_path": image_path,
        "trust_status": trust_result.get("trust_status"),
        "signer_id": trust_result.get("signer_id"),
        "key_id": trust_result.get("key_id"),
        "signer_backend": trust_result.get("signer_backend"),
        "payload_sha256": trust_result.get("payload_sha256"),
        "reason": trust_result.get("reason", ""),
        "policy_result": policy_result or {},
    }
    try:
        _audit_dir().mkdir(parents=True, exist_ok=True)
        with _audit_log_path().open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(event, sort_keys=True, separators=(",", ":")) + "\n")
        return {"logged": True, "path": str(_audit_log_path())}
    except Exception as exc:
        return {"logged": False, "reason": str(exc)}


def verify_trust_block_with_backend(
    trust_block: Dict[str, Any],
    *,
    payload_bytes: bytes,
    require_trust: bool = False,
) -> Dict[str, Any]:
    backend_name = trust_block.get("backend") if isinstance(trust_block, dict) else None
    backend_warning = ""
    try:
        backend = get_signer_backend(str(backend_name) if backend_name else None)
    except Exception:
        backend = LocalSignerBackend()
        backend_warning = f"Unknown signer backend '{backend_name}', fell back to local verification"

    result = backend.verify(trust_block, payload_bytes)
    result.setdefault("signer_backend", backend.backend_name)
    if backend_warning:
        result["backend_warning"] = backend_warning

    transparency = verify_transparency_event(
        trust_block if isinstance(trust_block, dict) else {},
        payload_sha256=result.get("payload_sha256", ""),
    )
    result["transparency_status"] = transparency.get("status")
    result["transparency_reason"] = transparency.get("reason", "")

    if require_trust and result.get("trust_status") != "trusted":
        reason = result.get("reason", "trusted artifact required")
        result["reason"] = f"{reason}; trusted artifact required"
    return result
