#!/usr/bin/env python3
"""
TPRM Directory - Main Application File for Spaceship Deployment
Third-Party Risk Management Vendor Directory

This is the main Flask application file optimized for deployment on Spaceship hosting.
"""

import os
import sqlite3
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS

# Initialize Flask application
app = Flask(__name__, static_folder='static', static_url_path='')

# Enable CORS for all routes
CORS(app)

# Configuration for production deployment
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'your-secret-key-change-in-production')
app.config['DATABASE'] = os.path.join(os.path.dirname(__file__), 'vendors.db')

def get_db_connection():
    """Get database connection with proper error handling"""
    try:
        conn = sqlite3.connect(app.config['DATABASE'])
        conn.row_factory = sqlite3.Row
        return conn
    except sqlite3.Error as e:
        print(f"Database connection error: {e}")
        return None

def init_db():
    """Initialize database if it doesn't exist"""
    if not os.path.exists(app.config['DATABASE']):
        print("Database not found. Please ensure vendors.db is uploaded to your hosting account.")
        return False
    return True

@app.route('/')
def index():
    """Serve the main application"""
    return send_from_directory(app.static_folder, 'index.html')

@app.route('/api/vendors')
def get_vendors():
    """Get all vendors with optional filtering and search"""
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'error': 'Database connection failed'}), 500
        
        # Get query parameters
        search = request.args.get('search', '').strip()
        category = request.args.get('category', '').strip()
        industry = request.args.get('industry', '').strip()
        
        # Build SQL query
        query = "SELECT * FROM vendors WHERE 1=1"
        params = []
        
        if search:
            query += " AND (name LIKE ? OR description LIKE ? OR services LIKE ?)"
            search_param = f"%{search}%"
            params.extend([search_param, search_param, search_param])
        
        if category:
            query += " AND category = ?"
            params.append(category)
        
        if industry:
            query += " AND industries_served LIKE ?"
            params.append(f"%{industry}%")
        
        # Order by premium status and rating
        query += " ORDER BY is_premium DESC, rating DESC, name ASC"
        
        cursor = conn.execute(query, params)
        vendors = []
        
        for row in cursor.fetchall():
            vendor = {
                'id': row['id'],
                'name': row['name'],
                'category': row['category'],
                'description': row['description'],
                'location': row['location'],
                'phone': row['phone'],
                'contact_email': row['contact_email'],
                'website': row['website'],
                'founded': row['founded'],
                'rating': row['rating'],
                'is_premium': bool(row['is_premium']),
                'risk_level': row['risk_level'],
                'certifications': row['certifications'],
                'industries_served': row['industries_served'],
                'services': row['services']
            }
            vendors.append(vendor)
        
        conn.close()
        return jsonify(vendors)
        
    except Exception as e:
        print(f"Error fetching vendors: {e}")
        return jsonify({'error': 'Failed to fetch vendors'}), 500

@app.route('/api/vendors/<int:vendor_id>')
def get_vendor(vendor_id):
    """Get a specific vendor by ID"""
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'error': 'Database connection failed'}), 500
        
        cursor = conn.execute("SELECT * FROM vendors WHERE id = ?", (vendor_id,))
        row = cursor.fetchone()
        
        if row:
            vendor = {
                'id': row['id'],
                'name': row['name'],
                'category': row['category'],
                'description': row['description'],
                'location': row['location'],
                'phone': row['phone'],
                'contact_email': row['contact_email'],
                'website': row['website'],
                'founded': row['founded'],
                'rating': row['rating'],
                'is_premium': bool(row['is_premium']),
                'risk_level': row['risk_level'],
                'certifications': row['certifications'],
                'industries_served': row['industries_served'],
                'services': row['services']
            }
            conn.close()
            return jsonify(vendor)
        else:
            conn.close()
            return jsonify({'error': 'Vendor not found'}), 404
            
    except Exception as e:
        print(f"Error fetching vendor: {e}")
        return jsonify({'error': 'Failed to fetch vendor'}), 500

@app.route('/api/categories')
def get_categories():
    """Get all unique categories"""
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'error': 'Database connection failed'}), 500
        
        cursor = conn.execute("SELECT DISTINCT category FROM vendors ORDER BY category")
        categories = [row['category'] for row in cursor.fetchall()]
        
        conn.close()
        return jsonify(categories)
        
    except Exception as e:
        print(f"Error fetching categories: {e}")
        return jsonify({'error': 'Failed to fetch categories'}), 500

@app.route('/api/health')
def health_check():
    """Health check endpoint"""
    return jsonify({
        'status': 'healthy',
        'message': 'TPRM Directory API is running',
        'database': 'connected' if get_db_connection() else 'disconnected'
    })

@app.errorhandler(404)
def not_found(error):
    """Handle 404 errors by serving the React app"""
    return send_from_directory(app.static_folder, 'index.html')

@app.errorhandler(500)
def internal_error(error):
    """Handle 500 errors"""
    return jsonify({'error': 'Internal server error'}), 500

# Initialize database on startup
with app.app_context():
    init_db()

if __name__ == '__main__':
    # For development only - Spaceship will use WSGI
    app.run(host='0.0.0.0', port=5000, debug=False)

