#!/usr/bin/env python3
"""
Image Integration Module

Handles product vs non-product image workflows.
Since image-generation and image-edit skills are removed, this module
provides utilities to find existing images and ask user to provide new ones.
"""

import os
import glob
import argparse
from typing import Optional, List


class ImageIntegration:
    def __init__(self, skills_base_path: str = ""):
        pass

    def find_product_images(self, product_name: str, website_repo: str) -> List[str]:
        """
        Find existing product images in website repo

        Args:
            product_name: Product name to search for
            website_repo: Path to website repository

        Returns:
            List of image paths
        """
        if not website_repo or not os.path.exists(website_repo):
            return []

        extensions = [".jpg", ".jpeg", ".png", ".webp"]
        found_images = []

        patterns = [
            f"**/*{product_name}*{{ext}}",
            f"public/images/**/*{{ext}}",
            f"src/assets/**/*{{ext}}",
        ]

        for pattern in patterns:
            for ext in extensions:
                search_pattern = pattern.format(ext=ext)
                matches = glob.glob(
                    os.path.join(website_repo, search_pattern), recursive=True
                )
                found_images.extend(matches[:5])

        return list(set(found_images))[:10]

    def handle_product_content(
        self, product_name: str, website_repo: str
    ) -> Optional[List[str]]:
        """Handle image for product content - returns found images for user to select"""
        print(f"\n🔍 Looking for product images: {product_name}")

        images = self.find_product_images(product_name, website_repo)

        if images:
            print(f"  ✓ Found {len(images)} image(s):")
            for i, img in enumerate(images[:5], 1):
                print(f"    {i}. {img}")
            return images
        else:
            print(f"  ✗ No product images found in repo")
            return None

    def suggest_non_product_image(self, content_type: str, topic: str) -> str:
        """
        Suggest image for non-product content

        Args:
            content_type: Type (service, stats, knowledge)
            topic: Topic name

        Returns:
            Suggestion message
        """
        suggestions = {
            "service": f"Please provide a professional service illustration for: {topic}",
            "stats": f"Please provide a data visualization/infographic image for: {topic}",
            "knowledge": f"Please provide an educational illustration for: {topic}",
            "default": f"Please provide an image for: {topic}",
        }

        return suggestions.get(content_type, suggestions["default"])


def main():
    """Test image integration"""
    parser = argparse.ArgumentParser(description="Test Image Integration")
    parser.add_argument("--action", choices=["find", "suggest"], required=True)
    parser.add_argument("--topic", help="Topic name")
    parser.add_argument("--product-name", help="Product name (for find action)")
    parser.add_argument("--website-repo", help="Website repo path (for find action)")
    parser.add_argument(
        "--content-type", default="default", help="Content type (for suggest action)"
    )

    args = parser.parse_args()

    integration = ImageIntegration()

    if args.action == "find":
        if not args.product_name or not args.website_repo:
            print("Error: --product-name and --website-repo required for find")
            return

        images = integration.find_product_images(args.product_name, args.website_repo)
        print(f"\nFound {len(images)} images:")
        for img in images:
            print(f"  - {img}")

    elif args.action == "suggest":
        suggestion = integration.suggest_non_product_image(
            args.content_type, args.topic or "your topic"
        )
        print(f"\n{suggestion}")


if __name__ == "__main__":
    main()
