from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_wtf.csrf import CSRFProtect
from config import config
from app.utils.rate_limit import limiter

db = SQLAlchemy()
migrate = Migrate()
csrf = CSRFProtect()

def create_app(config_name='development'):
    """Application factory"""
    app = Flask(__name__, template_folder='../templates')
    app.config.from_object(config[config_name])
    
    # Initialize extensions
    db.init_app(app)
    migrate.init_app(app, db)
    csrf.init_app(app)
    limiter.init_app(app)
    
    # Add security headers
    @app.after_request
    def set_security_headers(response):
        response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
        response.headers['X-Content-Type-Options'] = 'nosniff'
        response.headers['X-Frame-Options'] = 'DENY'
        response.headers['X-XSS-Protection'] = '1; mode=block'
        response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
        response.headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://www.google.com/ https://www.gstatic.com/ https://recaptcha.google.com/ https://static.cloudflareinsights.com/ https://challenges.cloudflare.com/; frame-src 'self' https://www.google.com/ https://recaptcha.google.com/ https://challenges.cloudflare.com/; connect-src 'self' https://www.google.com/ https://recaptcha.google.com/ https://www.gstatic.com/ https://challenges.cloudflare.com/; img-src 'self' data: https://www.gstatic.com/; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;"
        return response
    
    # Register blueprints
    from app.routes import auth_bp, register_blueprints
    register_blueprints(app)
    
    # ============ MAIN PAGES ============
    @app.route('/')
    def home():
        from flask import render_template
        return render_template('index.html')
    
    # ============ POLICY & INFORMATION PAGES ============
    
    @app.route('/privacy')
    def privacy():
        """Privacy Policy page"""
        from flask import render_template
        return render_template('privacy.html')
    
    
    @app.route('/terms')
    def terms():
        """Terms of Service page"""
        from flask import render_template
        return render_template('terms.html')
    
    
    @app.route('/cookies')
    def cookies():
        """Cookie Policy page"""
        from flask import render_template
        return render_template('cookies.html')
    
    
    @app.route('/about')
    def about():
        """About page"""
        from flask import render_template
        return render_template('about.html')
    
    
    @app.route('/contact', methods=['GET', 'POST'])
    def contact():
        """Contact page - displays form (GET) and handles submission (POST)"""
        from flask import render_template, request, jsonify
        import datetime
        
        if request.method == 'GET':
            return render_template('contact.html')
        
        if request.method == 'POST':
            # Extract form data
            name = request.form.get('name', '').strip()
            email = request.form.get('email', '').strip()
            phone = request.form.get('phone', '').strip()
            subject = request.form.get('subject', '').strip()
            message = request.form.get('message', '').strip()
            
            # Validation
            if not name or not email or not subject or not message:
                return jsonify({'success': False, 'error': 'Missing required fields'}), 400
            
            # Basic email validation
            if '@' not in email or '.' not in email:
                return jsonify({'success': False, 'error': 'Invalid email'}), 400
            
            try:
                # Log the submission
                print(f"\n=== NEW CONTACT SUBMISSION ===")
                print(f"Name: {name}")
                print(f"Email: {email}")
                print(f"Phone: {phone}")
                print(f"Subject: {subject}")
                print(f"Message: {message}")
                print(f"Timestamp: {datetime.datetime.now()}")
                print(f"================================\n")
                
                # TODO: Implement email sending
                # Example for future email integration:
                # send_email(
                #     to='support@getfoundlocal.app',
                #     subject=f'New Contact Form: {subject}',
                #     body=f'From: {name} ({email})\nPhone: {phone}\n\n{message}'
                # )
                # send_confirmation_email(to=email, name=name)
                
                return jsonify({'success': True}), 200
            
            except Exception as e:
                print(f"Error processing contact form: {str(e)}")
                return jsonify({'success': False, 'error': 'Server error'}), 500
    
    
    # ============ ERROR HANDLERS ============
    
    @app.errorhandler(404)
    def not_found(error):
        from flask import render_template
        return render_template('errors/404.html'), 404
    
    
    @app.errorhandler(500)
    def server_error(error):
        from flask import render_template
        return render_template('errors/500.html'), 500
    
    
    @app.errorhandler(403)
    def forbidden(error):
        from flask import render_template
        return render_template('errors/403.html'), 403
    
    
    return app