from flask import render_template, request, flash, redirect, url_for, jsonify
from app import app, db
from models import ContactSubmission, NewsletterSubscription
from forms import ContactForm, NewsletterForm
import logging

@app.route('/')
def index():
    """Homepage showcasing PrismaOS overview"""
    return render_template('index.html', title='PrismaOS - Accessible Mobile Operating System')

@app.route('/features')
def features():
    """Accessibility features showcase"""
    return render_template('features.html', title='Accessibility Features - PrismaOS')

@app.route('/technical')
def technical():
    """Technical documentation and architecture"""
    return render_template('technical.html', title='Technical Documentation - PrismaOS')

@app.route('/sdk')
def sdk():
    """Developer SDK information and resources"""
    return render_template('sdk.html', title='Developer SDK - PrismaOS')

@app.route('/community')
def community():
    """Community engagement and resources"""
    return render_template('community.html', title='Community - PrismaOS')

@app.route('/roadmap')
def roadmap():
    """Development roadmap and timeline"""
    return render_template('roadmap.html', title='Development Roadmap - PrismaOS')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    """Contact form with accessibility features"""
    form = ContactForm()
    
    if form.validate_on_submit():
        try:
            # Save contact submission to database
            submission = ContactSubmission(
                name=form.name.data,
                email=form.email.data,
                subject=form.subject.data,
                message=form.message.data,
                accessibility_needs=form.accessibility_needs.data
            )
            db.session.add(submission)
            db.session.commit()
            
            flash('Thank you for your message! We will respond within 24 hours.', 'success')
            logging.info(f"Contact form submitted by {form.email.data}")
            return redirect(url_for('contact'))
            
        except Exception as e:
            db.session.rollback()
            flash('There was an error sending your message. Please try again.', 'error')
            logging.error(f"Error saving contact form: {e}")
    
    return render_template('contact.html', title='Contact Us - PrismaOS', form=form)

@app.route('/newsletter', methods=['POST'])
def newsletter_signup():
    """Newsletter subscription endpoint"""
    form = NewsletterForm()
    
    if form.validate_on_submit():
        try:
            # Check if email already exists
            existing = NewsletterSubscription.query.filter_by(email=form.email.data).first()
            if existing:
                flash('You are already subscribed to our newsletter.', 'info')
            else:
                subscription = NewsletterSubscription(email=form.email.data)
                db.session.add(subscription)
                db.session.commit()
                flash('Successfully subscribed to PrismaOS updates!', 'success')
                logging.info(f"Newsletter subscription: {form.email.data}")
                
        except Exception as e:
            db.session.rollback()
            flash('There was an error with your subscription. Please try again.', 'error')
            logging.error(f"Error saving newsletter subscription: {e}")
    else:
        flash('Please enter a valid email address.', 'error')
    
    return redirect(request.referrer or url_for('index'))

@app.errorhandler(404)
def page_not_found(e):
    """Custom 404 error page with accessibility features"""
    return render_template('base.html', 
                         title='Page Not Found - PrismaOS',
                         error_message='The page you are looking for could not be found.'), 404

@app.errorhandler(500)
def internal_server_error(e):
    """Custom 500 error page"""
    return render_template('base.html',
                         title='Server Error - PrismaOS',
                         error_message='An internal server error occurred. Please try again later.'), 500

# Accessibility helper routes
@app.route('/skip-links')
def skip_links():
    """Information about skip links and keyboard navigation"""
    return jsonify({
        'skip_links': [
            {'target': '#main-content', 'text': 'Skip to main content'},
            {'target': '#navigation', 'text': 'Skip to navigation'},
            {'target': '#footer', 'text': 'Skip to footer'}
        ],
        'keyboard_shortcuts': [
            {'key': 'Tab', 'action': 'Navigate forward through interactive elements'},
            {'key': 'Shift + Tab', 'action': 'Navigate backward through interactive elements'},
            {'key': 'Enter/Space', 'action': 'Activate buttons and links'},
            {'key': 'Escape', 'action': 'Close modals and menus'}
        ]
    })
