import os
import sys
import urllib.parse

# 1. Base directory setup
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

# 2. Redirect PyMuPDF messages to /dev/null
os.environ["PYMUPDF_MESSAGE"] = "path:/dev/null"

# 3. Security Access Code Config
ACCESS_CODE = "31337"
AUTH_COOKIE_NAME = "km_auth_31337"

# 4. Post-fork lazy application loader
_app_instance = None

def get_app():
    global _app_instance
    if _app_instance is None:
        from a2wsgi import ASGIMiddleware
        from server.main import app
        _app_instance = ASGIMiddleware(app)
    return _app_instance

def application(environ, start_response):
    path_info = environ.get("PATH_INFO", "/")
    query_str = environ.get("QUERY_STRING", "")
    params = urllib.parse.parse_qs(query_str)
    provided_code = params.get("code", [""])[0]
    
    cookies = environ.get("HTTP_COOKIE", "")
    has_valid_cookie = f"{AUTH_COOKIE_NAME}=1" in cookies
    
    referer = environ.get("HTTP_REFERER", "")
    has_valid_referer = "dev.enivid.eu" in referer or "enivid" in referer
    
    is_static = path_info.startswith("/static/")

    is_authorized = (
        (provided_code == ACCESS_CODE) or 
        has_valid_cookie or 
        has_valid_referer or 
        is_static
    )
    should_set_cookie = (provided_code == ACCESS_CODE)

    if not is_authorized:
        if path_info.startswith("/api/"):
            # Return JSON for API calls
            status = "403 Forbidden"
            headers = [("Content-Type", "application/json; charset=utf-8")]
            start_response(status, headers)
            return [b'{"detail": "Authentication required. Please refresh with ?code=31337"}']

        # Return HTML Passcode Unlock Screen for browser visits
        status = "403 Forbidden"
        headers = [("Content-Type", "text/html; charset=utf-8")]
        start_response(status, headers)
        html = """<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Access Restricted — KM-1 Estimator</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Inter', -apple-system, sans-serif;
      background: radial-gradient(circle at 50% 30%, #0f172a, #020617);
      color: #f8fafc;
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
      margin: 0;
      padding: 1.5rem;
      box-sizing: border-box;
    }
    .auth-card {
      background: rgba(30, 41, 59, 0.85);
      backdrop-filter: blur(16px);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 16px;
      padding: 2.5rem 2rem;
      width: 100%;
      max-width: 380px;
      text-align: center;
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.6);
    }
    .lock-icon {
      width: 56px;
      height: 56px;
      background: rgba(14, 165, 233, 0.15);
      border: 1px solid rgba(14, 165, 233, 0.3);
      color: #38bdf8;
      border-radius: 14px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 1.25rem;
    }
    h2 { font-size: 1.35rem; font-weight: 700; margin: 0 0 0.5rem; color: #fff; }
    p { font-size: 0.85rem; color: #94a3b8; margin: 0 0 1.75rem; line-height: 1.4; }
    input[type="password"] {
      width: 100%;
      padding: 0.85rem 1rem;
      margin-bottom: 1rem;
      background: #090d16;
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 8px;
      color: #fff;
      font-size: 1.1rem;
      letter-spacing: 3px;
      text-align: center;
      box-sizing: border-box;
      outline: none;
      transition: border-color 0.2s;
    }
    input[type="password"]:focus { border-color: #38bdf8; }
    button {
      width: 100%;
      padding: 0.85rem;
      background: linear-gradient(135deg, #0284c7, #0369a1);
      border: none;
      border-radius: 8px;
      color: #fff;
      font-weight: 600;
      font-size: 0.95rem;
      cursor: pointer;
      box-shadow: 0 4px 15px rgba(2, 132, 199, 0.4);
      transition: opacity 0.2s;
    }
    button:hover { opacity: 0.9; }
  </style>
</head>
<body>
  <div class="auth-card">
    <div class="lock-icon">
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
      </svg>
    </div>
    <h2>Access Restricted</h2>
    <p>Please enter the security passkey to access this environment.</p>
    <form method="GET" action="/">
      <input type="password" name="code" placeholder="•••••" autofocus required autocomplete="off">
      <button type="submit">Unlock Application</button>
    </form>
  </div>
</body>
</html>"""
        return [html.encode("utf-8")]

    # 6. User is Authorized -> Dispatch to FastAPI
    app_middleware = get_app()

    def wrapped_start_response(status, response_headers, exc_info=None):
        if should_set_cookie:
            cookie_header = f"{AUTH_COOKIE_NAME}=1; Path=/; Max-Age=2592000; SameSite=Lax"
            response_headers.append(("Set-Cookie", cookie_header))
        return start_response(status, response_headers, exc_info)

    response = app_middleware(environ, wrapped_start_response)
    body = []
    try:
        for chunk in response:
            if chunk:
                body.append(chunk)
    finally:
        if hasattr(response, "close"):
            response.close()
    return body
