from flask import Flask, jsonify, request, send_from_directory, send_file
import os

app = Flask(__name__)

# Import our archive parser
from parse_archive import ArchiveParser

# Initialize the archive parser
archive_parser = ArchiveParser()

# Serve static files from the root directory
@app.route("/<path:filename>")
def serve_static(filename):
    try:
        return send_from_directory(".", filename)
    except FileNotFoundError:
        return jsonify({"error": "File not found"}), 404

# Serve the main index.html page
@app.route("/")
def serve_index():
    return send_file("index.html")

@app.route("/posts", methods=["GET"])
def get_initial_posts():
    """Get the first 10 posts for initial load"""
    try:
        # Use archive parser to fetch posts
        posts = archive_parser.get_posts(count=10, start_index=0)
        filters_posts = []
        for p in posts:
            if p["title"] is not None:
                filters_posts += [p]
        return jsonify(filters_posts)
    except Exception as e:
        print(f"Error: {e}")
        return jsonify({"error": "Failed to fetch posts"}), 500

@app.route("/posts/more", methods=["GET"])
def get_more_posts():
    """Get next 10 posts based on the count parameter"""
    try:
        # Get the count parameter from query string, default to 10
        count = request.args.get("count", 10, type=int)

        # Use archive parser to fetch posts
        posts = archive_parser.get_posts(count=10, start_index=count)
        filters_posts = []
        for p in posts:
            if p["title"] is not None:
                filters_posts += [p]
        return jsonify(filters_posts)
    except Exception as e:
        print(f"Error: {e}")
        return jsonify({"error": "Failed to fetch more posts"}), 500

@app.route("/posts/total", methods=["GET"])
def get_total_posts():
    """Get the total number of posts available"""
    try:
        # Get total from archive parser
        total = archive_parser.get_total_posts()
        return jsonify({"total": total})
    except Exception as e:
        print(f"Error: {e}")
        return jsonify({"error": "Failed to fetch total count"}), 500

@app.route("/api")
def home():
    """Home endpoint to verify server is running"""
    return jsonify(
        {
            "message": "Reddit Clone API Server is running",
            "endpoints": {
                "GET /posts": "Get first 10 posts",
                "GET /posts/more?count=N": "Get next 10 posts, starting from index N",
                "GET /posts/total": "Get total number of posts",
            },
        }
    )

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