"""Command-line interface for MoreStore"""

import argparse
import sys
import json
from pathlib import Path

from morestore_cli.client import MoreStoreClient


def main():
    """Main CLI entry point"""
    parser = argparse.ArgumentParser(
        description="MoreStore CLI - AI-powered brand and product analysis tools",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s analyze-brand https://example.com
  %(prog)s perfect-scene image.jpg --output result.jpg
  %(prog)s analyze-product image.jpg --brand-name "My Brand"
  %(prog)s perfect-ad image.jpg --product-name "Product Name"
        """
    )
    
    # Global arguments (available to all commands)
    parser.add_argument(
        '--api-url',
        type=str,
        default='https://morestore.ai',
        help='Base URL of the MoreStore API (default: https://morestore.ai)'
    )
    
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Analyze Brand command
    analyze_brand_parser = subparsers.add_parser(
        'analyze-brand',
        help='Analyze a brand website',
        description='Perform AI-powered brand identity analysis'
    )
    analyze_brand_parser.add_argument('website_url', help='URL of the website to analyze')
    analyze_brand_parser.add_argument('--clear-cache', action='store_true', help='Force fresh analysis')
    analyze_brand_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Get Analysis command
    get_analysis_parser = subparsers.add_parser(
        'get-analysis',
        help='Get cached analysis for a domain',
        description='Retrieve previously cached brand analysis'
    )
    get_analysis_parser.add_argument('domain', help='Domain name (e.g., example.com)')
    get_analysis_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Clear Cache command
    clear_cache_parser = subparsers.add_parser(
        'clear-cache',
        help='Clear cached analysis',
        description='Clear cached analysis for a domain'
    )
    clear_cache_parser.add_argument('domain', help='Domain name (e.g., example.com)')
    
    # Analyze Product command
    analyze_product_parser = subparsers.add_parser(
        'analyze-product',
        help='Analyze a product image',
        description='Extract product metadata and generate SEO keywords'
    )
    analyze_product_parser.add_argument('image', help='Path to product image file')
    analyze_product_parser.add_argument('--brand-name', help='Brand name for context')
    analyze_product_parser.add_argument('--product-name', help='Product name')
    analyze_product_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Batch Analyze Products command
    batch_analyze_parser = subparsers.add_parser(
        'batch-analyze-products',
        help='Analyze multiple products',
        description='Batch analyze products with streaming progress'
    )
    batch_analyze_parser.add_argument('products_file', help='JSON file with products array')
    batch_analyze_parser.add_argument('--no-progress', action='store_true', help='Disable progress updates')
    batch_analyze_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Perfect Prompt command
    perfect_prompt_parser = subparsers.add_parser(
        'perfect-prompt',
        help='Generate perfect prompt for a product',
        description='Generate AI-optimized scene prompts'
    )
    perfect_prompt_parser.add_argument('image', help='Path to product image file')
    perfect_prompt_parser.add_argument('--brand-name', help='Brand name')
    perfect_prompt_parser.add_argument('--product-name', help='Product name')
    perfect_prompt_parser.add_argument('--color', help='Color preference (e.g., "warm tones", "blue")')
    perfect_prompt_parser.add_argument('--theme', help='Theme preference (e.g., "modern", "vintage")')
    perfect_prompt_parser.add_argument('--suggestion', help='User suggestion for prompt generation')
    perfect_prompt_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Perfect Ad command
    perfect_ad_parser = subparsers.add_parser(
        'perfect-ad',
        help='Generate perfect ad with text overlay',
        description='Create ads with AI-generated text and optimal placement'
    )
    perfect_ad_parser.add_argument('image', help='Path to product image file')
    perfect_ad_parser.add_argument('--output', '-o', help='Output image path (default: input name with "_ad" suffix)')
    perfect_ad_parser.add_argument('--brand-name', help='Brand name')
    perfect_ad_parser.add_argument('--product-name', help='Product name')
    
    # Perfect Scene command
    perfect_scene_parser = subparsers.add_parser(
        'perfect-scene',
        help='Generate a perfect scene for a product image',
        description='Generate a perfect scene for a product image using AI'
    )
    perfect_scene_parser.add_argument('image', help='Path to the input image file (JPG or PNG)')
    perfect_scene_parser.add_argument('--output', '-o', help='Path to save the generated image (default: input name with "_perfect_scene" suffix)')
    perfect_scene_parser.add_argument('--brand-name', help='Brand name for better context')
    perfect_scene_parser.add_argument('--product-name', help='Product name')
    perfect_scene_parser.add_argument('--custom-prompt', help='Custom prompt for scene generation (auto-generated if not provided)')
    perfect_scene_parser.add_argument('--scale-to-megapixels', type=float, default=1.0, help='Target megapixels for image scaling (default: 1.0)')
    perfect_scene_parser.add_argument('--no-progress', action='store_true', help='Disable progress updates')
    
    # Batch Scenes command
    batch_scenes_parser = subparsers.add_parser(
        'batch-scenes',
        help='Generate perfect scenes for multiple products',
        description='Batch generate perfect scenes with streaming progress'
    )
    batch_scenes_parser.add_argument('images', nargs='+', help='Paths to product image files')
    batch_scenes_parser.add_argument('--scene-prompts', help='JSON array of scene prompts (one per image)')
    batch_scenes_parser.add_argument('--no-progress', action='store_true', help='Disable progress updates')
    
    # Batch Seasonal command
    batch_seasonal_parser = subparsers.add_parser(
        'batch-seasonal',
        help='Generate seasonal hero images',
        description='Generate seasonal marketing images'
    )
    batch_seasonal_parser.add_argument('products_file', help='JSON file with products array (name and image_url)')
    batch_seasonal_parser.add_argument('season', choices=['halloween', 'christmas', 'spring', 'summer', 'autumn', 'winter'], help='Season name')
    batch_seasonal_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Closest Brands command
    closest_brands_parser = subparsers.add_parser(
        'closest-brands',
        help='Find brands with similar identity',
        description='Find similar brands using semantic embeddings'
    )
    closest_brands_parser.add_argument('domain', help='Domain to find similar brands for')
    closest_brands_parser.add_argument('--top-k', type=int, default=5, help='Number of similar brands to return (default: 5)')
    closest_brands_parser.add_argument('--keep-model-loaded', action='store_true', help='Keep model in memory')
    closest_brands_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Farthest Brands command
    farthest_brands_parser = subparsers.add_parser(
        'farthest-brands',
        help='Find brands with contrasting identity',
        description='Find contrasting brands for differentiation'
    )
    farthest_brands_parser.add_argument('domain', help='Domain to find contrasting brands for')
    farthest_brands_parser.add_argument('--top-k', type=int, default=5, help='Number of contrasting brands to return (default: 5)')
    farthest_brands_parser.add_argument('--output', '-o', help='Output JSON file path (optional)')
    
    # Add --api-url to all subparsers
    for subparser in subparsers._name_parser_map.values():
        subparser.add_argument(
            '--api-url',
            type=str,
            default='https://morestore.ai',
            help='Base URL of the MoreStore API (default: https://morestore.ai)'
        )
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        sys.exit(1)
    
    # Initialize client (get api_url from args, default if not set)
    api_url = getattr(args, 'api_url', 'https://morestore.ai')
    client = MoreStoreClient(base_url=api_url)
    
    # Execute command
    try:
        if args.command == 'analyze-brand':
            result = client.analyze_brand(args.website_url, clear_cache=args.clear_cache)
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        elif args.command == 'get-analysis':
            result = client.get_analysis(args.domain)
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        elif args.command == 'clear-cache':
            result = client.clear_cache(args.domain)
            print(json.dumps(result, indent=2))
            print(f"\n✅ Cache cleared for {args.domain}")
        
        elif args.command == 'analyze-product':
            result = client.analyze_product(
                args.image,
                brand_name=args.brand_name,
                product_name=args.product_name
            )
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        elif args.command == 'batch-analyze-products':
            with open(args.products_file, 'r') as f:
                products_data = json.load(f)
            products = products_data.get('products', products_data)
            result = client.batch_analyze_products(products, show_progress=not args.no_progress)
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        elif args.command == 'perfect-prompt':
            result = client.generate_perfect_prompt(
                args.image,
                brand_name=args.brand_name,
                product_name=args.product_name,
                color=args.color,
                theme=args.theme,
                suggestion=args.suggestion
            )
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        elif args.command == 'perfect-ad':
            output_path = client.generate_perfect_ad(
                args.image,
                output_path=args.output,
                brand_name=args.brand_name,
                product_name=args.product_name
            )
            print(f"\n✅ Success! Generated ad saved to: {output_path}")
        
        elif args.command == 'perfect-scene':
            output_path = client.generate_perfect_scene(
                image_path=args.image,
                output_path=args.output,
                brand_name=args.brand_name,
                product_name=args.product_name,
                custom_prompt=args.custom_prompt,
                scale_to_megapixels=args.scale_to_megapixels,
                show_progress=not args.no_progress
            )
            print(f"\n✅ Success! Generated image saved to: {output_path}")
        
        elif args.command == 'batch-scenes':
            scene_prompts = None
            if args.scene_prompts:
                scene_prompts = json.loads(args.scene_prompts)
            result = client.batch_generate_perfect_scenes(
                args.images,
                scene_prompts=scene_prompts,
                show_progress=not args.no_progress
            )
            print(json.dumps(result, indent=2))
        
        elif args.command == 'batch-seasonal':
            with open(args.products_file, 'r') as f:
                products_data = json.load(f)
            products = products_data.get('products', products_data)
            result = client.generate_batch_seasonal(products, args.season)
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        elif args.command == 'closest-brands':
            result = client.closest_brands(
                args.domain,
                top_k=args.top_k,
                keep_model_loaded=args.keep_model_loaded
            )
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        elif args.command == 'farthest-brands':
            result = client.farthest_brands(args.domain, top_k=args.top_k)
            print(json.dumps(result, indent=2))
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(result, f, indent=2)
                print(f"\n✅ Saved to: {args.output}")
        
        sys.exit(0)
    
    except FileNotFoundError as e:
        print(f"❌ Error: {e}", file=sys.stderr)
        sys.exit(1)
    
    except json.JSONDecodeError as e:
        print(f"❌ JSON Error: {e}", file=sys.stderr)
        sys.exit(1)
    
    except Exception as e:
        print(f"❌ Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    main()

