#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================================================
ভূমি ও বর্গা হিসাব খতিয়ান (VUMI SOFTWARE) - WEB BACKEND & CLOUD SERVER
=============================================================================
Zero-dependency, production-grade Python server with:
- SQLite database persistence with WAL mode
- User authentication & session management (PBKDF2-SHA256)
- RESTful Cloud Sync endpoints (/api/data, /api/auth, /api/backup, /api/restore)
- Static file serving from /public directory
- WSGI compatibility for cPanel CloudLinux Passenger (passenger_wsgi.py)
- Standalone multi-threaded HTTP server for local & VPS execution
"""

import os
import sys
import json
import sqlite3
import hashlib
import hmac
import secrets
import mimetypes
from datetime import datetime, timedelta, timezone
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from urllib.parse import urlparse, parse_qs

# =============================================================================
# CONFIGURATION & PATHS
# =============================================================================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, 'data')
PUBLIC_DIR = os.path.join(BASE_DIR, 'public')
DB_PATH = os.path.join(DATA_DIR, 'vumi.db')
PORT = int(os.environ.get('PORT', 8000))
SESSION_DAYS = 30

os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(PUBLIC_DIR, exist_ok=True)

# =============================================================================
# DATABASE LAYER
# =============================================================================
def get_db():
    conn = sqlite3.connect(DB_PATH, check_same_thread=False)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA foreign_keys=ON;")
    return conn

def init_db():
    conn = get_db()
    with conn:
        conn.execute("""
            CREATE TABLE IF NOT EXISTS vumi_store (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS vumi_users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                salt TEXT NOT NULL,
                name TEXT NOT NULL,
                role TEXT NOT NULL DEFAULT 'admin',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS vumi_sessions (
                token TEXT PRIMARY KEY,
                user_id INTEGER NOT NULL,
                expires_at TIMESTAMP NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY(user_id) REFERENCES vumi_users(id) ON DELETE CASCADE
            );
        """)

        # Seed default admin user if none exists
        cur = conn.cursor()
        cur.execute("SELECT COUNT(*) FROM vumi_users;")
        if cur.fetchone()[0] == 0:
            salt = secrets.token_hex(16)
            pwd_hash = hash_password('admin123', salt)
            cur.execute("""
                INSERT INTO vumi_users (username, password_hash, salt, name, role)
                VALUES (?, ?, ?, ?, ?)
            """, ('admin', pwd_hash, salt, 'এডমিন', 'admin'))
            conn.commit()
    conn.close()

def hash_password(password: str, salt_hex: str) -> str:
    return hashlib.pbkdf2_hmac(
        'sha256',
        password.encode('utf-8'),
        bytes.fromhex(salt_hex),
        100000
    ).hex()

def verify_password(password: str, salt_hex: str, expected_hash: str) -> bool:
    candidate_hash = hash_password(password, salt_hex)
    return hmac.compare_digest(candidate_hash, expected_hash)

# Initialize database tables on import
init_db()

# =============================================================================
# AUTH & SESSION HELPERS
# =============================================================================
def authenticate_user(username, password):
    conn = get_db()
    try:
        cur = conn.cursor()
        cur.execute("SELECT id, username, password_hash, salt, name, role FROM vumi_users WHERE username = ?", (username,))
        row = cur.fetchone()
        if not row:
            return None
        if verify_password(password, row['salt'], row['password_hash']):
            return {
                'id': row['id'],
                'username': row['username'],
                'name': row['name'],
                'role': row['role']
            }
        return None
    finally:
        conn.close()

def create_session(user_id):
    token = secrets.token_hex(32)
    expires_at = datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)
    conn = get_db()
    try:
        with conn:
            conn.execute("""
                INSERT INTO vumi_sessions (token, user_id, expires_at)
                VALUES (?, ?, ?)
            """, (token, user_id, expires_at.isoformat()))
        return token
    finally:
        conn.close()

def get_session_user(token):
    if not token:
        return None
    conn = get_db()
    try:
        cur = conn.cursor()
        cur.execute("""
            SELECT u.id, u.username, u.name, u.role, s.expires_at
            FROM vumi_sessions s
            JOIN vumi_users u ON s.user_id = u.id
            WHERE s.token = ?
        """, (token,))
        row = cur.fetchone()
        if not row:
            return None
        
        # Check expiration
        exp_str = row['expires_at']
        try:
            exp_dt = datetime.fromisoformat(exp_str)
            if exp_dt.tzinfo is None:
                exp_dt = exp_dt.replace(tzinfo=timezone.utc)
            if datetime.now(timezone.utc) > exp_dt:
                conn.execute("DELETE FROM vumi_sessions WHERE token = ?", (token,))
                conn.commit()
                return None
        except Exception:
            pass

        return {
            'id': row['id'],
            'username': row['username'],
            'name': row['name'],
            'role': row['role']
        }
    finally:
        conn.close()

def revoke_session(token):
    if not token:
        return
    conn = get_db()
    try:
        with conn:
            conn.execute("DELETE FROM vumi_sessions WHERE token = ?", (token,))
    finally:
        conn.close()

def parse_cookie_header(cookie_header):
    cookies = {}
    if not cookie_header:
        return cookies
    for part in cookie_header.split(';'):
        if '=' in part:
            k, v = part.strip().split('=', 1)
            cookies[k] = v
    return cookies

def extract_token(headers):
    # Check Authorization: Bearer <token>
    auth = headers.get('authorization', '')
    if auth.startswith('Bearer '):
        return auth[7:].strip()
    # Check Cookie header
    cookie_str = headers.get('cookie', '')
    cookies = parse_cookie_header(cookie_str)
    return cookies.get('vumi_session') or cookies.get('session_token') or ''

# =============================================================================
# REQUEST DISPATCHER (SHARED BY STANDALONE HTTP & WSGI)
# =============================================================================
class Request:
    def __init__(self, method, path, query_params, headers, body_bytes):
        self.method = method.upper()
        self.path = path
        self.query_params = query_params
        self.headers = {k.lower(): v for k, v in headers.items()}
        self.body_bytes = body_bytes

    def json(self):
        try:
            return json.loads(self.body_bytes.decode('utf-8'))
        except Exception:
            return {}

class Response:
    def __init__(self, status=200, headers=None, body=b''):
        self.status = status
        self.headers = headers or []
        self.body = body

    @classmethod
    def json(cls, data, status=200, extra_headers=None):
        payload = json.dumps(data, ensure_ascii=False).encode('utf-8')
        headers = [
            ('Content-Type', 'application/json; charset=utf-8'),
            ('Content-Length', str(len(payload))),
            ('Cache-Control', 'no-store, no-cache, must-revalidate')
        ]
        if extra_headers:
            headers.extend(extra_headers)
        return cls(status=status, headers=headers, body=payload)

    @classmethod
    def text(cls, text, status=200):
        payload = text.encode('utf-8')
        headers = [
            ('Content-Type', 'text/plain; charset=utf-8'),
            ('Content-Length', str(len(payload)))
        ]
        return cls(status=status, headers=headers, body=payload)

def handle_request(req: Request) -> Response:
    path = req.path
    if path == '':
        path = '/'

    # -------------------------------------------------------------------------
    # API ROUTES
    # -------------------------------------------------------------------------
    if path.startswith('/api/'):
        # 1. Login
        if path == '/api/auth/login' and req.method == 'POST':
            data = req.json()
            username = (data.get('username') or '').strip()
            password = (data.get('password') or '').strip()
            if not username or not password:
                return Response.json({'success': False, 'message': 'ইউজারনেম ও পাসওয়ার্ড আবশ্যক'}, status=400)
            user = authenticate_user(username, password)
            if not user:
                return Response.json({'success': False, 'message': 'ভুল ইউজারনেম অথবা পাসওয়ার্ড'}, status=401)
            token = create_session(user['id'])
            cookie_hdr = ('Set-Cookie', f'vumi_session={token}; Path=/; Max-Age={SESSION_DAYS*86400}; SameSite=Lax; HttpOnly')
            return Response.json({
                'success': True,
                'token': token,
                'user': user
            }, extra_headers=[cookie_hdr])

        # 2. Logout
        if path == '/api/auth/logout' and req.method == 'POST':
            token = extract_token(req.headers)
            revoke_session(token)
            cookie_hdr = ('Set-Cookie', 'vumi_session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT')
            return Response.json({'success': True}, extra_headers=[cookie_hdr])

        # 3. Current User (/api/auth/me)
        if path == '/api/auth/me' and req.method == 'GET':
            token = extract_token(req.headers)
            user = get_session_user(token)
            if not user:
                return Response.json({'success': False, 'message': 'অনুগ্রহ করে লগইন করুন'}, status=401)
            return Response.json({'success': True, 'user': user, 'token': token})

        # Protected Endpoints Check
        token = extract_token(req.headers)
        current_user = get_session_user(token)
        if not current_user:
            return Response.json({'success': False, 'message': 'অনুমতি নেই। অনুগ্রহ করে লগইন করুন'}, status=401)

        # 4. Change Password
        if path == '/api/auth/change-password' and req.method == 'POST':
            data = req.json()
            old_pwd = data.get('oldPassword', '')
            new_pwd = data.get('newPassword', '')
            if len(new_pwd) < 4:
                return Response.json({'success': False, 'message': 'নতুন পাসওয়ার্ড ন্যূনতম ৪ অক্ষরের হতে হবে'}, status=400)
            conn = get_db()
            try:
                cur = conn.cursor()
                cur.execute("SELECT password_hash, salt FROM vumi_users WHERE id = ?", (current_user['id'],))
                u_row = cur.fetchone()
                if not verify_password(old_pwd, u_row['salt'], u_row['password_hash']):
                    return Response.json({'success': False, 'message': 'বর্তমান পাসওয়ার্ড সঠিক নয়'}, status=400)
                new_salt = secrets.token_hex(16)
                new_hash = hash_password(new_pwd, new_salt)
                conn.execute("UPDATE vumi_users SET password_hash = ?, salt = ? WHERE id = ?", (new_hash, new_salt, current_user['id']))
                conn.commit()
                return Response.json({'success': True, 'message': 'পাসওয়ার্ড সফলভাবে পরিবর্তন করা হয়েছে'})
            finally:
                conn.close()

        # 5. Get All Data (/api/data)
        if path == '/api/data' and req.method == 'GET':
            conn = get_db()
            try:
                cur = conn.cursor()
                cur.execute("SELECT key, value FROM vumi_store")
                rows = cur.fetchall()
                out = {}
                for r in rows:
                    raw_val = r['value']
                    try:
                        out[r['key']] = json.loads(raw_val)
                    except Exception:
                        out[r['key']] = raw_val
                return Response.json({'success': True, 'data': out})
            finally:
                conn.close()

        # 6. Save Data (/api/data)
        if path == '/api/data' and req.method == 'POST':
            payload = req.json()
            if not isinstance(payload, dict):
                return Response.json({'success': False, 'message': 'অবৈধ ডেটা ফরম্যাট'}, status=400)
            conn = get_db()
            try:
                with conn:
                    for k, v in payload.items():
                        v_str = v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
                        conn.execute("""
                            INSERT INTO vumi_store (key, value, updated_at)
                            VALUES (?, ?, CURRENT_TIMESTAMP)
                            ON CONFLICT(key) DO UPDATE SET
                                value = excluded.value,
                                updated_at = CURRENT_TIMESTAMP
                        """, (k, v_str))
                return Response.json({'success': True, 'saved': len(payload)})
            finally:
                conn.close()

        # 7. Backup Download (/api/backup)
        if path == '/api/backup' and req.method == 'GET':
            conn = get_db()
            try:
                cur = conn.cursor()
                cur.execute("SELECT key, value FROM vumi_store")
                rows = cur.fetchall()
                store_dict = {}
                for r in rows:
                    try:
                        store_dict[r['key']] = json.loads(r['value'])
                    except Exception:
                        store_dict[r['key']] = r['value']
                backup_data = {
                    'app': 'land-dashboard',
                    'version': 1,
                    'exportedAt': datetime.now(timezone.utc).isoformat(),
                    'data': {
                        'records': store_dict.get('land-records-v2', []),
                        'lists': store_dict.get('land-lists-v2', {}),
                        'bontonRecords': store_dict.get('land-bonton-ijmali-v1', []),
                        'malikanaRecords': store_dict.get('land-malikana-v1', []),
                        'khajnaRecords': store_dict.get('land-khajna-v1', []),
                        'settings': store_dict.get('land-settings-v1', {})
                    }
                }
                body = json.dumps(backup_data, ensure_ascii=False, indent=2).encode('utf-8')
                today_str = datetime.now().strftime('%Y-%m-%d')
                headers = [
                    ('Content-Type', 'application/json; charset=utf-8'),
                    ('Content-Disposition', f'attachment; filename="vumi-backup-{today_str}.json"'),
                    ('Content-Length', str(len(body)))
                ]
                return Response(status=200, headers=headers, body=body)
            finally:
                conn.close()

        # 8. Restore Data (/api/restore)
        if path == '/api/restore' and req.method == 'POST':
            payload = req.json()
            data = payload.get('data') if (isinstance(payload, dict) and 'data' in payload) else payload
            if not isinstance(data, dict):
                return Response.json({'success': False, 'message': 'অবৈধ ব্যাকআপ ফাইল'}, status=400)
            key_map = {
                'records': 'land-records-v2',
                'lists': 'land-lists-v2',
                'bontonRecords': 'land-bonton-ijmali-v1',
                'malikanaRecords': 'land-malikana-v1',
                'khajnaRecords': 'land-khajna-v1',
                'settings': 'land-settings-v1'
            }
            conn = get_db()
            count = 0
            try:
                with conn:
                    for src_key, target_store_key in key_map.items():
                        if src_key in data:
                            val_str = json.dumps(data[src_key], ensure_ascii=False)
                            conn.execute("""
                                INSERT INTO vumi_store (key, value, updated_at)
                                VALUES (?, ?, CURRENT_TIMESTAMP)
                                ON CONFLICT(key) DO UPDATE SET
                                    value = excluded.value,
                                    updated_at = CURRENT_TIMESTAMP
                            """, (target_store_key, val_str))
                            count += 1
                return Response.json({'success': True, 'restored': count, 'message': 'ডেটা সফলভাবে রিস্টোর হয়েছে'})
            finally:
                conn.close()

        return Response.json({'success': False, 'message': 'API endpoint not found'}, status=404)

    # -------------------------------------------------------------------------
    # STATIC FILES SERVING FROM /public
    # -------------------------------------------------------------------------
    rel_path = path.lstrip('/')
    if not rel_path or rel_path == 'index.html':
        file_path = os.path.join(PUBLIC_DIR, 'index.html')
    else:
        # Prevent directory traversal attacks
        safe_rel = os.path.normpath(rel_path).lstrip(os.path.sep).lstrip('/')
        if '..' in safe_rel:
            return Response.text('Forbidden', status=403)
        file_path = os.path.join(PUBLIC_DIR, safe_rel)

    # If file exists, serve it
    if os.path.isfile(file_path):
        mime, _ = mimetypes.guess_type(file_path)
        mime = mime or 'application/octet-stream'
        if mime.startswith('text/') or mime in ('application/javascript', 'application/json'):
            mime += '; charset=utf-8'
        try:
            with open(file_path, 'rb') as f:
                content = f.read()
            headers = [
                ('Content-Type', mime),
                ('Content-Length', str(len(content))),
                ('Cache-Control', 'public, max-age=3600' if not file_path.endswith('.html') else 'no-cache')
            ]
            return Response(status=200, headers=headers, body=content)
        except Exception as e:
            return Response.text(f'Internal Server Error: {e}', status=500)

    # Fallback to index.html for Single Page Application client routing
    index_path = os.path.join(PUBLIC_DIR, 'index.html')
    if os.path.isfile(index_path):
        with open(index_path, 'rb') as f:
            content = f.read()
        headers = [
            ('Content-Type', 'text/html; charset=utf-8'),
            ('Content-Length', str(len(content))),
            ('Cache-Control', 'no-cache')
        ]
        return Response(status=200, headers=headers, body=content)

    return Response.text('Not Found', status=404)

# =============================================================================
# WSGI APPLICATION INTERFACE (FOR CPANEL CLOUDLINUX PASSENGER)
# =============================================================================
STATUS_MAP = {
    200: '200 OK',
    201: '201 Created',
    400: '400 Bad Request',
    401: '401 Unauthorized',
    403: '403 Forbidden',
    404: '404 Not Found',
    500: '500 Internal Server Error'
}

def application(environ, start_response):
    method = environ.get('REQUEST_METHOD', 'GET')
    path = environ.get('PATH_INFO', '/')
    query_string = environ.get('QUERY_STRING', '')
    query_params = parse_qs(query_string)

    headers = {}
    content_length = 0
    for k, v in environ.items():
        if k.startswith('HTTP_'):
            headers[k[5:].replace('_', '-').lower()] = v
        elif k in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
            headers[k.replace('_', '-').lower()] = v
            if k == 'CONTENT_LENGTH' and v.isdigit():
                content_length = int(v)

    body_bytes = b''
    if content_length > 0 and 'wsgi.input' in environ:
        body_bytes = environ['wsgi.input'].read(content_length)

    req = Request(method, path, query_params, headers, body_bytes)
    res = handle_request(req)

    status_str = STATUS_MAP.get(res.status, f'{res.status} Response')
    start_response(status_str, res.headers)
    return [res.body]

# =============================================================================
# STANDALONE HTTP SERVER (FOR LOCAL & VPS DEPLOYMENT)
# =============================================================================
class VumiHTTPRequestHandler(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'

    def log_message(self, format, *args):
        # Clean logging
        sys.stdout.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {args[0]} {args[1]} -> {args[2]}\n")

    def do_request(self):
        parsed = urlparse(self.path)
        query_params = parse_qs(parsed.query)

        length = int(self.headers.get('Content-Length', 0))
        body_bytes = self.rfile.read(length) if length > 0 else b''

        req = Request(self.command, parsed.path, query_params, dict(self.headers), body_bytes)
        res = handle_request(req)

        self.send_response(res.status)
        for k, v in res.headers:
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(res.body)

    do_GET = do_request
    do_POST = do_request
    do_PUT = do_request
    do_DELETE = do_request
    do_OPTIONS = do_request

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    daemon_threads = True

def run_server(port=PORT):
    server = ThreadedHTTPServer(('0.0.0.0', port), VumiHTTPRequestHandler)
    print("=" * 65)
    print(f" 🌾 ভূমি ও বর্গা হিসাব খতিয়ান (VUMI SOFTWARE) ওয়েব সার্ভার চালু হয়েছে")
    print(f" 👉 লোকাল ইউআরএল: http://localhost:{port}")
    print(f" 👉 নেটওয়ার্ক ইউআরএল: http://0.0.0.0:{port}")
    print(f" 🔑 ডিফল্ট ইউজারনেম: admin")
    print(f" 🔑 ডিফল্ট পাসওয়ার্ড: admin123")
    print(f" 💾 ডেটাবেস ফাইল: {DB_PATH}")
    print("=" * 65)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nসার্ভার বন্ধ করা হচ্ছে...")
        server.server_close()

if __name__ == '__main__':
    run_server()
