from flask import Flask, render_template_string, request, jsonify, session, redirect
from .renderer.html_generator import HTMLGenerator
from .utils.state import StateManager
import os


class FeatherServer:
    def __init__(self, app):
        self.feather_app = app
        self.flask_app = Flask(__name__)
        self.flask_app.secret_key = os.environ.get('SESSION_SECRET', 'feather-dev-secret-key')
        self.html_generator = HTMLGenerator()
        self.setup_routes()
    
    def setup_routes(self):
        """Set up Flask routes from FeatherOS app"""
        
        @self.flask_app.route('/', methods=['GET', 'POST'])
        @self.flask_app.route('/<path:path>', methods=['GET', 'POST'])
        def handle_page(path='/'):
            if not path.startswith('/'):
                path = '/' + path
            
            if path in self.feather_app.pages:
                from .utils.state import _state_manager
                _state_manager.init_session()
                
                if request.method == 'POST':
                    _state_manager.set_form_data(request.form.to_dict())
                    html_content = self.render_page(path)
                    
                    if _state_manager.should_rerun:
                        _state_manager.should_rerun = False
                        return redirect(request.url)
                    
                    return html_content
                else:
                    html_content = self.render_page(path)
                    return html_content
            else:
                return f"<h1>404 - Page Not Found</h1><p>Path '{path}' is not registered.</p>", 404
        
        for api_path, api_func in self.feather_app.api_routes.items():
            def make_api_handler(func):
                def handler():
                    result = func()
                    return jsonify(result)
                return handler
            
            self.flask_app.add_url_rule(
                api_path,
                endpoint=api_path,
                view_func=make_api_handler(api_func),
                methods=['GET', 'POST']
            )
    
    def render_page(self, path: str) -> str:
        """Render a FeatherOS page to HTML"""
        page_func = self.feather_app.pages.get(path)
        
        if not page_func:
            return "<h1>404</h1>"
        
        self.html_generator.reset()
        
        page_func()
        
        html = self.html_generator.generate_html(self.feather_app.title)
        return html
    
    def run(self, host: str = "0.0.0.0", port: int = 5000, debug: bool = True):
        """Start the Flask server"""
        self.flask_app.run(host=host, port=port, debug=debug)
