# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Gallery Vault skill — artwork watermarking, provenance, and chain notarization.

Provides 5 tools for managing a digital art gallery with blockchain-backed
provenance certificates. Supports visible overlay watermarks, LSB steganography,
and SHA-256 integrity verification anchored to the genesis block chain.
"""

import json
import logging
from pathlib import Path

logger = logging.getLogger(__name__)


def _get_gallery_dir():
    """Get gallery data directory."""
    from familiar.core.paths import DATA_DIR

    gallery = DATA_DIR / "gallery"
    for sub in ("originals", "watermarked", "thumbnails", "certificates"):
        (gallery / sub).mkdir(parents=True, exist_ok=True)
    return gallery


def _load_gallery_data() -> list:
    """Load gallery.json artwork registry."""
    data_file = _get_gallery_dir() / "gallery.json"
    if data_file.exists():
        try:
            return json.loads(data_file.read_text())
        except (json.JSONDecodeError, OSError):
            pass
    return []


# ── Tool Handlers ─────────────────────────────────────────────


def watermark_art(data: dict) -> dict:
    """Apply watermark(s) to an image file."""
    from familiar.skills.gallery.watermark import (
        apply_invisible_watermark,
        apply_visible_watermark,
        compute_image_hash,
    )

    image_path = data.get("image_path", "")
    if not image_path or not Path(image_path).exists():
        return {"error": "Image file not found", "success": False}

    text = data.get("text", "")
    wm_type = data.get("type", "visible")
    position = data.get("position", "bottom-right")
    opacity = data.get("opacity", 0.3)
    output_path = data.get("output_path", "")

    try:
        original_hash = compute_image_hash(image_path)

        if wm_type == "invisible":
            embed_data = data.get("data", text or f"Watermarked: {image_path}")
            result_path = apply_invisible_watermark(
                image_path, embed_data, output_path=output_path
            )
        else:
            if not text:
                return {"error": "Watermark text is required for visible watermarks"}
            result_path = apply_visible_watermark(
                image_path, text,
                position=position,
                opacity=opacity,
                output_path=output_path,
            )

        watermarked_hash = compute_image_hash(result_path)

        return {
            "success": True,
            "output_path": result_path,
            "type": wm_type,
            "original_hash": original_hash,
            "watermarked_hash": watermarked_hash,
        }
    except Exception as e:
        return {"error": str(e), "success": False}


def register_artwork_tool(data: dict) -> dict:
    """Register artwork in gallery with chain notarization."""
    from familiar.skills.gallery.provenance import register_artwork

    image_path = data.get("image_path", "")
    if not image_path or not Path(image_path).exists():
        return {"error": "Image file not found", "success": False}

    title = data.get("title", "Untitled")
    artist = data.get("artist", "Unknown")

    try:
        artwork = register_artwork(
            image_path=image_path,
            title=title,
            artist=artist,
            description=data.get("description", ""),
            medium=data.get("medium", ""),
            dimensions=data.get("dimensions", ""),
            license_type=data.get("license", "All Rights Reserved"),
            tags=data.get("tags", []),
            watermark_types=data.get("watermark_types", ["visible", "invisible", "certificate"]),
        )
        return {
            "success": True,
            "artwork_id": artwork["artwork_id"],
            "title": artwork["title"],
            "artist": artwork["artist"],
            "block_hash": artwork.get("block_hash", ""),
            "watermark_types": artwork["watermark_types"],
            "certificate_path": artwork.get("certificate_path", ""),
            "message": f"Registered '{title}' by {artist} with {len(artwork['watermark_types'])} watermark(s)",
        }
    except Exception as e:
        return {"error": str(e), "success": False}


def verify_artwork_tool(data: dict) -> dict:
    """Verify provenance chain for artwork."""
    from familiar.skills.gallery.provenance import verify_artwork

    artwork_id = data.get("artwork_id", "")
    if not artwork_id:
        return {"error": "artwork_id is required", "success": False}

    try:
        result = verify_artwork(artwork_id)
        return {"success": True, **result}
    except Exception as e:
        return {"error": str(e), "success": False}


def gallery_list(data: dict) -> dict:
    """List all gallery vault contents."""
    artworks = _load_gallery_data()

    items = []
    for a in artworks:
        items.append({
            "artwork_id": a["artwork_id"],
            "title": a["title"],
            "artist": a["artist"],
            "registered_at": a.get("registered_at", ""),
            "watermark_types": a.get("watermark_types", []),
            "block_hash": a.get("block_hash", ""),
            "thumbnail_path": a.get("thumbnail_path", ""),
            "tags": a.get("tags", []),
        })

    return {
        "success": True,
        "count": len(items),
        "artworks": items,
    }


def gallery_search(data: dict) -> dict:
    """Search gallery by title, artist, or tags."""
    artworks = _load_gallery_data()
    query = data.get("query", "").lower().strip()

    if not query:
        return gallery_list(data)

    matches = []
    for a in artworks:
        searchable = " ".join([
            a.get("title", ""),
            a.get("artist", ""),
            a.get("description", ""),
            a.get("medium", ""),
            " ".join(a.get("tags", [])),
        ]).lower()

        if query in searchable:
            matches.append({
                "artwork_id": a["artwork_id"],
                "title": a["title"],
                "artist": a["artist"],
                "registered_at": a.get("registered_at", ""),
                "watermark_types": a.get("watermark_types", []),
                "block_hash": a.get("block_hash", ""),
                "tags": a.get("tags", []),
            })

    return {
        "success": True,
        "query": query,
        "count": len(matches),
        "artworks": matches,
    }


# ── Tool Definitions ──────────────────────────────────────────

TOOLS = [
    {
        "name": "watermark_art",
        "description": (
            "Apply a watermark to an image file. Supports visible text overlay "
            "(with position and opacity control) and invisible LSB steganography."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "image_path": {
                    "type": "string",
                    "description": "Path to the image file to watermark",
                },
                "text": {
                    "type": "string",
                    "description": "Watermark text (required for visible type)",
                },
                "type": {
                    "type": "string",
                    "enum": ["visible", "invisible"],
                    "description": "Watermark type: visible overlay or invisible LSB steganography",
                    "default": "visible",
                },
                "position": {
                    "type": "string",
                    "enum": ["bottom-right", "bottom-left", "center", "tiled"],
                    "description": "Position for visible watermark",
                    "default": "bottom-right",
                },
                "opacity": {
                    "type": "number",
                    "description": "Opacity for visible watermark (0.0–1.0)",
                    "default": 0.3,
                },
                "data": {
                    "type": "string",
                    "description": "Data to embed for invisible watermark",
                },
                "output_path": {
                    "type": "string",
                    "description": "Output file path (auto-generated if empty)",
                },
            },
            "required": ["image_path"],
        },
        "handler": watermark_art,
        "category": "gallery",
    },
    {
        "name": "register_artwork",
        "description": (
            "Register artwork in the Gallery Vault with blockchain notarization. "
            "Applies watermarks, generates a provenance certificate, and anchors "
            "the registration to the genesis block chain."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "image_path": {
                    "type": "string",
                    "description": "Path to the artwork image file",
                },
                "title": {
                    "type": "string",
                    "description": "Title of the artwork",
                },
                "artist": {
                    "type": "string",
                    "description": "Name of the artist",
                },
                "description": {
                    "type": "string",
                    "description": "Description of the artwork",
                },
                "medium": {
                    "type": "string",
                    "description": "Medium (e.g., digital, oil, watercolor)",
                },
                "dimensions": {
                    "type": "string",
                    "description": "Dimensions (e.g., 1920x1080, 24x36 inches)",
                },
                "license": {
                    "type": "string",
                    "description": "License type",
                    "default": "All Rights Reserved",
                },
                "tags": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Tags for searching",
                },
                "watermark_types": {
                    "type": "array",
                    "items": {
                        "type": "string",
                        "enum": ["visible", "invisible", "certificate"],
                    },
                    "description": "Watermark types to apply",
                    "default": ["visible", "invisible", "certificate"],
                },
            },
            "required": ["image_path", "title", "artist"],
        },
        "handler": register_artwork_tool,
        "category": "gallery",
    },
    {
        "name": "verify_artwork",
        "description": (
            "Verify the provenance chain integrity for a registered artwork. "
            "Re-hashes the watermarked image and checks the chain block."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "artwork_id": {
                    "type": "string",
                    "description": "The artwork ID to verify",
                },
            },
            "required": ["artwork_id"],
        },
        "handler": verify_artwork_tool,
        "category": "gallery",
    },
    {
        "name": "gallery_list",
        "description": "List all artworks in the Gallery Vault with metadata and chain status.",
        "input_schema": {
            "type": "object",
            "properties": {},
        },
        "handler": gallery_list,
        "category": "gallery",
    },
    {
        "name": "gallery_search",
        "description": "Search the Gallery Vault by title, artist, tags, or description.",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query to match against title, artist, tags, and description",
                },
            },
            "required": ["query"],
        },
        "handler": gallery_search,
        "category": "gallery",
    },
]
