from flask import Flask, request, jsonify
from tag_identification import TagIdentifier
from tag_match import TagMatcher
from image_similarity import ImageSimilarity
import os
import time

app = Flask(__name__)

# Initialize components
print("Initializing Tag Scan System...")
tag_identifier = TagIdentifier()
tag_matcher = TagMatcher('data/tag_guides_clean.json')
image_similarity = ImageSimilarity('data/expert_data.csv', 'data/community_data.csv')
print("System initialized successfully!")


@app.route('/')
def home():
    return jsonify({
        'message': 'DS Task Tag Scan System API',
        'version': '1.0',
        'endpoints': {
            '/get_tag': 'POST - Analyze tag image and find similar tags',
            '/status': 'GET - Health check'
        }
    })


@app.route('/get_tag', methods=['POST'])
def get_tag():
    start_time = time.time()
    
    try:
        # Validate request
        data = request.get_json()
        if not data or 'image_url' not in data:
            return jsonify({'error': 'Missing image_url in request'}), 400
            
        image_url = data['image_url']
        
        # Load and process image
        print(f"Processing image: {image_url}")
        image = tag_identifier.load_image(image_url)
        
        # Identify brand and extract text
        brand, extracted_text = tag_identifier.identify_brand(image)
        print(f"Identified brand: {brand}, Extracted text: {extracted_text}")
        
        # Find text-based matches using extracted text or brand
        search_query = extracted_text if extracted_text else brand
        text_matches = tag_matcher.find_matches(search_query)
        
        # Find visually similar images
        image_matches = image_similarity.find_similar(image_url)
        
        # Format response
        results = []
        
        # Add text-based matches
        for match in text_matches:
            results.append({
                "tag": match["name"],
                "year_start": str(match["year_start"]) if match["year_start"] else "unknown",
                "year_end": str(match["year_end"]) if match["year_end"] else "unknown",
                "match_type": "text",
                "confidence": match.get("confidence", 0.0)
            })
        
        # Add image similarity results
        if image_matches:
            similar_images_data = {
                "similar_images": [img["image_url"] for img in image_matches],
                "appraisal_value": [img["appraisal_value"] for img in image_matches],
                "years": [img["year"] for img in image_matches],
                "status": ["public" if img["status"] == 1 else "private" for img in image_matches],
                "brands": [img["brand_name"] for img in image_matches],
                "similarity_scores": [img["similarity_score"] for img in image_matches],
                "match_type": "visual"
            }
            results.append(similar_images_data)
        
        # Calculate processing time
        processing_time = time.time() - start_time
        
        response = {
            "success": True,
            "results": results,
            "metadata": {
                "identified_brand": brand,
                "extracted_text": extracted_text,
                "processing_time_seconds": round(processing_time, 2),
                "total_matches": len(text_matches) + len(image_matches)
            }
        }
        
        print(f"Request completed in {processing_time:.2f} seconds")
        return jsonify(response)
        
    except ValueError as ve:
        # Handle image loading errors
        return jsonify({
            'success': False,
            'error': f'Image processing error: {str(ve)}'
        }), 400
        
    except Exception as e:
        # Handle other errors
        print(f"Unexpected error: {e}")
        return jsonify({
            'success': False,
            'error': f'Internal server error: {str(e)}'
        }), 500


@app.route('/status', methods=['GET'])
def status():
    """Health check endpoint"""
    try:
        # Quick system check
        system_status = {
            'status': 'healthy',
            'components': {
                'tag_identifier': 'ready',
                'tag_matcher': 'ready',
                'image_similarity': 'ready'
            },
            'database_stats': {
                'tag_guides': len(tag_matcher.data) if hasattr(tag_matcher, 'data') else 0,
                'image_database': len(image_similarity.image_data) if hasattr(image_similarity, 'image_data') else 0
            }
        }
        return jsonify(system_status)
        
    except Exception as e:
        return jsonify({
            'status': 'unhealthy',
            'error': str(e)
        }), 503


@app.route('/favicon.ico')
def favicon():
    return '', 404


if __name__ == '__main__':
    print("Starting DS Task Tag Scan System...")
    app.run(host='0.0.0.0', port=5000, debug=False)