"""WSGI entry point for the application."""

import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

from shopdb import create_app

app = create_app(os.environ.get('FLASK_ENV', 'development'))


class MountPathMiddleware:
    """Serve the whole app (API + SPA) under a URL prefix, e.g. '/ops'.

    Used when the app is deployed as an IIS Application under an existing
    site instead of its own site: IIS forwards the full request path
    ('/ops/api/...'), so the prefix is moved from PATH_INFO to SCRIPT_NAME
    before Flask routes it. Flask then also generates URLs under the prefix.
    The frontend must be built with the matching VITE_BASE_PATH ('/ops/').
    """

    def __init__(self, wsgi_app, mountpath):
        self.wsgi_app = wsgi_app
        self.mountpath = '/' + mountpath.strip('/')

    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO', '')
        if path == self.mountpath or path.startswith(self.mountpath + '/'):
            environ['SCRIPT_NAME'] = environ.get('SCRIPT_NAME', '') + self.mountpath
            environ['PATH_INFO'] = path[len(self.mountpath):] or '/'
            return self.wsgi_app(environ, start_response)
        start_response('404 Not Found', [('Content-Type', 'text/plain')])
        return [b'Not Found: the app is mounted at ' + self.mountpath.encode() + b'/']


# MOUNT_PATH (.env or web.config) activates the subpath deployment method.
# Unset/empty = the app owns the server root (its own IIS site; the default).
_mountpath = os.environ.get('MOUNT_PATH', '').strip()
if _mountpath and _mountpath != '/':
    app.wsgi_app = MountPathMiddleware(app.wsgi_app, _mountpath)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=True)
