import os
import sqlite3
from datetime import datetime
from flask import (
    Flask,
    render_template,
    request,
    redirect,
    url_for,
    flash,
    send_from_directory,
)
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.secret_key = os.urandom(24)

# Configure upload folder
UPLOAD_FOLDER = "static/uploads"
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif"}
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


def get_db():
    db = sqlite3.connect("pet_pictures.db")
    db.row_factory = sqlite3.Row
    return db


def init_db():
    with get_db() as db:
        db.execute(
            """
            CREATE TABLE IF NOT EXISTS pet_pictures (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                filename TEXT NOT NULL,
                subscriber_name TEXT NOT NULL,
                uploaded_at TIMESTAMP NOT NULL,
                posted BOOLEAN DEFAULT 0
            )
        """
        )
        db.commit()


def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route("/")
def index():
    with get_db() as db:
        pictures = db.execute(
            "SELECT * FROM pet_pictures ORDER BY uploaded_at DESC"
        ).fetchall()
    return render_template("index.html", pictures=pictures)


@app.route("/upload", methods=["GET", "POST"])
def upload():
    if request.method == "POST":
        if "picture" not in request.files:
            flash("No file selected")
            return redirect(request.url)

        file = request.files["picture"]
        subscriber_name = request.form.get("subscriber_name")

        if file.filename == "":
            flash("No file selected")
            return redirect(request.url)

        if not subscriber_name:
            flash("Subscriber name is required")
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_")
            filename = timestamp + filename
            file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))

            with get_db() as db:
                db.execute(
                    "INSERT INTO pet_pictures (filename, subscriber_name, uploaded_at) VALUES (?, ?, ?)",
                    (filename, subscriber_name, datetime.now()),
                )
                db.commit()

            flash("Picture uploaded successfully!")
            return redirect(url_for("index"))

        flash("Invalid file type")
        return redirect(request.url)

    return render_template("upload.html")


@app.route("/mark_posted/<int:picture_id>", methods=["POST"])
def mark_posted(picture_id):
    with get_db() as db:
        db.execute("UPDATE pet_pictures SET posted = 1 WHERE id = ?", (picture_id,))
        db.commit()
    flash("Picture marked as posted!")
    return redirect(url_for("index"))


@app.route("/download/<filename>")
def download_file(filename):
    return send_from_directory(
        app.config["UPLOAD_FOLDER"], filename, as_attachment=True
    )


if __name__ == "__main__":
    init_db()
    app.run(debug=True)
