import os
import json
import time
from flask import Flask, request, jsonify, send_from_directory, session
from flask_cors import CORS
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import secrets
import string
from functools import wraps

app = Flask(__name__)
app.secret_key = secrets.token_hex(24)
# Alias for Namecheap Passenger
application = app
# More permissive CORS for Namecheap Passenger
CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})

PORT = 5000
BACKEND_DIR = os.path.dirname(os.path.abspath(__file__))
WEBSITE_DIR = os.path.join(BACKEND_DIR, '..')
UPLOADS_DIR = os.path.join(BACKEND_DIR, 'uploads')
DB_FILE = os.path.join(BACKEND_DIR, 'gallery.json')
INQUIRIES_FILE = os.path.join(BACKEND_DIR, 'inquiries.json')
EMAIL_CONFIG_FILE = os.path.join(BACKEND_DIR, 'email_config.json')
ADMIN_CONFIG_FILE = os.path.join(BACKEND_DIR, 'admin_config.json')

def get_admin_credentials():
    """Loads or creates admin credentials."""
    if not os.path.exists(ADMIN_CONFIG_FILE):
        # Generate a new 25-character password
        password = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(25))
        config = {
            "username": "admin",
            "password": password, # Store plain for user to see in file
            "hashed_password": generate_password_hash(password)
        }
        with open(ADMIN_CONFIG_FILE, 'w') as f:
            json.dump(config, f, indent=4)
        print(f"[!] NEW ADMIN PASSWORD GENERATED: {password}")
        print(f"[!] PLEASE CHECK {ADMIN_CONFIG_FILE} FOR YOUR CREDENTIALS.")
        return config
    
    with open(ADMIN_CONFIG_FILE, 'r') as f:
        return json.load(f)

# Initialize admin config
ADMIN_CREDENTIALS = get_admin_credentials()

def get_base_url():
    """Determines the correct base URL for images based on environment."""
    # Check if we are on local
    if 'localhost' in request.host or '127.0.0.1' in request.host:
        return f"http://{request.host}"
    
    # On Namecheap, we want to return the actual domain
    # If the domain is https://udec.com.ng, we return that
    scheme = request.headers.get('X-Forwarded-Proto', 'https')
    return f"{scheme}://{request.host}"

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'logged_in' not in session:
            return jsonify({"error": "Authentication required"}), 401
        return f(*args, **kwargs)
    return decorated_function

@app.route('/api/login', methods=['POST'])
@app.route('/login', methods=['POST'])
def login():
    try:
        data = request.json
        username = data.get('username', '').strip()
        password = data.get('password', '').strip()
        
        # Reload credentials from disk every time to avoid caching issues
        credentials = get_admin_credentials()
        
        # Log for debugging (will show in stderr.log in cPanel)
        print(f"Login attempt for user: {username}")
        
        stored_user = credentials.get('username', 'admin')
        stored_pass = credentials.get('password', '')
        stored_hash = credentials.get('hashed_password', '')
        
        # Robust comparison: check plain text first, then hash
        is_valid = False
        if username == stored_user:
            if password == stored_pass:
                is_valid = True
            elif stored_hash and check_password_hash(stored_hash, password):
                is_valid = True
        
        if is_valid:
            session['logged_in'] = True
            session.permanent = True # Make session last longer
            return jsonify({"success": True, "message": "Login successful"})
        
        return jsonify({"error": "Invalid username or password"}), 401
    except Exception as e:
        print(f"Login error: {str(e)}")
        return jsonify({"error": f"Server Error: {str(e)}"}), 500

@app.route('/api/logout', methods=['POST'])
@app.route('/logout', methods=['POST'])
def logout():
    session.pop('logged_in', None)
    return jsonify({"success": True, "message": "Logged out"})

@app.route('/api/check-auth', methods=['GET'])
@app.route('/check-auth', methods=['GET'])
def check_auth():
    return jsonify({"authenticated": 'logged_in' in session})

def send_email_notification(inquiry_data):
    """Sends an email notification if config exists."""
    if not os.path.exists(EMAIL_CONFIG_FILE):
        return False
    try:
        with open(EMAIL_CONFIG_FILE, 'r') as f:
            config = json.load(f)
        sender_email = config.get('email')
        app_password = config.get('app_password')
        receiver_email = config.get('receiver', 'enquries@udecltd.com')
        if not sender_email or not app_password:
            return False
        msg = MIMEMultipart()
        msg['From'] = sender_email
        msg['To'] = receiver_email
        msg['Subject'] = f"New Inquiry: {inquiry_data.get('Fullname', 'No Name')}"
        body = f"""
        New Inquiry Received!
        Full Name: {inquiry_data.get('Fullname')}
        Email: {inquiry_data.get('_replyto')}
        Message: {inquiry_data.get('Message')}
        Timestamp: {inquiry_data.get('timestamp')}
        """
        msg.attach(MIMEText(body, 'plain'))
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
            server.login(sender_email, app_password)
            server.send_message(msg)
        return True
    except Exception as e:
        print(f"[!] Email Error: {e}")
        return False

# Ensure directories exist
os.makedirs(UPLOADS_DIR, exist_ok=True)

@app.route('/api/contact', methods=['POST'])
@app.route('/contact', methods=['POST'])
def handle_contact():
    try:
        data = request.json
        data['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
        inquiries = []
        if os.path.exists(INQUIRIES_FILE):
            with open(INQUIRIES_FILE, 'r') as f:
                inquiries = json.load(f)
        inquiries.append(data)
        with open(INQUIRIES_FILE, 'w') as f:
            json.dump(inquiries, f, indent=4)
        send_email_notification(data)
        return jsonify({"success": True, "message": "Inquiry received"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def init_db():
    if not os.path.exists(DB_FILE):
        initial_data = []
        # Scan for existing images
        for filename in os.listdir(WEBSITE_DIR):
            if filename.lower().endswith('.jpg') and any(word in filename.lower() for word in ['project', 'bespoke', 'marble', 'island']):
                initial_data.append({
                    "id": int(time.time() * 1000) + len(initial_data),
                    "title": filename.replace('.jpg', ''),
                    "imageUrl": f"/api/initial/{filename}",
                    "filename": filename,
                    "isInitial": True
                })
        with open(DB_FILE, 'w') as f:
            json.dump(initial_data, f, indent=4)

init_db()

@app.route('/api/gallery', methods=['GET'])
@app.route('/gallery', methods=['GET'])
def get_gallery():
    if os.path.exists(DB_FILE):
        with open(DB_FILE, 'r') as f:
            data = json.load(f)
            # Fix image URLs for current environment
            base = get_base_url()
            for item in data:
                if item.get('isInitial'):
                    item['imageUrl'] = f"{base}/api/initial/{item['filename']}"
                else:
                    item['imageUrl'] = f"{base}/api/uploads/{item['filename']}"
            return jsonify(data)
    return jsonify([])

@app.route('/api/gallery', methods=['POST'])
@app.route('/gallery', methods=['POST'])
@login_required
def upload_image():
    if 'image' not in request.files:
        return jsonify({"error": "No image uploaded"}), 400
    
    file = request.files['image']
    title = request.form.get('title', 'New Project')
    
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    
    filename = f"{int(time.time())}-{secure_filename(file.filename)}"
    file.save(os.path.join(UPLOADS_DIR, filename))
    
    new_item = {
        "id": int(time.time() * 1000),
        "title": title,
        "imageUrl": f"{get_base_url()}/api/uploads/{filename}",
        "filename": filename,
        "isInitial": False
    }
    
    data = []
    if os.path.exists(DB_FILE):
        with open(DB_FILE, 'r') as f:
            data = json.load(f)
    
    data.append(new_item)
    with open(DB_FILE, 'w') as f:
        json.dump(data, f, indent=4)
        
    return jsonify(new_item), 201

@app.route('/api/gallery/<int:item_id>', methods=['DELETE'])
@app.route('/gallery/<int:item_id>', methods=['DELETE'])
@login_required
def delete_image(item_id):
    if not os.path.exists(DB_FILE):
        return jsonify({"error": "DB not found"}), 404
        
    with open(DB_FILE, 'r') as f:
        data = json.load(f)
        
    item = next((x for x in data if x['id'] == item_id), None)
    if not item:
        return jsonify({"error": "Item not found"}), 404
        
    # Delete from disk
    file_path = os.path.join(WEBSITE_DIR if item['isInitial'] else UPLOADS_DIR, item['filename'])
    if os.path.exists(file_path):
        os.remove(file_path)
        
    # Update JSON
    data = [x for x in data if x['id'] != item_id]
    with open(DB_FILE, 'w') as f:
        json.dump(data, f, indent=4)
        
    return jsonify({"message": "Deleted successfully"})

@app.route('/api/uploads/<path:filename>')
@app.route('/uploads/<path:filename>')
def serve_uploads(filename):
    return send_from_directory(UPLOADS_DIR, filename)

@app.route('/api/initial/<path:filename>')
@app.route('/initial/<path:filename>')
def serve_initial(filename):
    return send_from_directory(WEBSITE_DIR, filename)

if __name__ == '__main__':
    app.run(port=PORT, debug=True)
