from flask import Flask, request, render_template, redirect, url_for
from ..modules.html_extractor.extract import get_content_from_url
from flask_dance.contrib.google import make_google_blueprint, google

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['PREFIX'] = '/proxy/5000'

app.config['GOOGLE_OAUTH_CLIENT_ID'] = 'your-client-id'
app.config['GOOGLE_OAUTH_CLIENT_SECRET'] = 'your-client-secret'

@app.route("/")
def index():
    print("index!")
    return render_template("index.html", prefix=app.config['PREFIX'],)


@app.route("/page")
def article_page():
    url = request.args.get("url")
    if not url:
        return redirect(url_for('index'))
    
    try:
        content = get_content_from_url(url)
        return render_template('page.html', 
                            prefix=app.config['PREFIX'],
                            url=url,
                            summary=content,
                            audio_url="/static/audio/sample.mp3")
    
    except Exception as e:
        app.logger.error(f"Error processing {url}: {str(e)}")
        return render_template('error.html', 
                            error_message="Failed to process the URL"), 500

@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Add authentication logic here
        return redirect(url_for('index'))
    return render_template("login.html", prefix=app.config['PREFIX'])

@app.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        # Add registration logic here
        return redirect(url_for('login'))
    return render_template("register.html", prefix=app.config['PREFIX'])

@app.errorhandler(404)
def page_not_found(e):
    return render_template('error.html', prefix=app.config['PREFIX'],
                         error_message="Page not found"), 404

@app.errorhandler(500)
def internal_error(e):
    return render_template('error.html', prefix=app.config['PREFIX'],
                         error_message="Internal server error"), 500



google_bp = make_google_blueprint(
    scope=["profile", "email"],
    redirect_to="auth_callback"
)
app.register_blueprint(google_bp, url_prefix="/auth")

@app.route("/auth/callback")
def auth_callback():
    if not google.authorized:
        return redirect(url_for("login"))
    
    resp = google.get("/oauth2/v2/userinfo")
    if resp.ok:
        user_info = resp.json()
        # Handle user authentication logic here
        return redirect(url_for("index"))
    
    return redirect(url_for("login"))

@app.route("/auth/google")
def google_auth():
    return redirect(url_for("google.login"))

if __name__ == "__main__":
    app.run(port=5000, debug=True)
