from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3
import os
import datetime

BASE_DIR = os.path.dirname(__file__)
DB_PATH = os.path.join(BASE_DIR, 'hiddencode.db')

def get_conn():
    return sqlite3.connect(DB_PATH)

app = Flask(__name__)
CORS(app)

@app.route('/write', methods=['POST'])
def write():
    data = request.get_json() or {}
    sha = data.get('sha')
    upload = data.get('upload_code')
    download = data.get('download_code')
    if not sha:
        return jsonify({'status':'error','msg':'missing sha'}), 400
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    conn = get_conn()
    c = conn.cursor()
    try:
        # upsert by sha
        c.execute('''
            INSERT INTO codes (sha, upload_code, download_code, created_at)
            VALUES (?,?,?,?)
            ON CONFLICT(sha) DO UPDATE SET upload_code=excluded.upload_code, download_code=excluded.download_code, created_at=excluded.created_at
        ''', (sha, upload, download, now))
        conn.commit()
    finally:
        conn.close()
    return jsonify({'status':'ok'})

@app.route('/read', methods=['POST'])
def read():
    data = request.get_json() or {}
    shas = data.get('shas', [])
    conn = get_conn()
    c = conn.cursor()
    result = {}
    if shas:
        placeholders = ','.join('?' for _ in shas)
        c.execute(f"SELECT sha, upload_code, download_code, created_at FROM codes WHERE sha IN ({placeholders})", shas)
        rows = c.fetchall()
        for sha, up, down, created in rows:
            result[sha] = {'upload_code': up, 'download_code': down, 'created_at': created}
    for s in shas:
        if s not in result:
            result[s] = None
    conn.close()
    return jsonify({'status':'ok','data':result})

@app.route('/health', methods=['GET'])
def health():
    return jsonify({'status':'ok'})

if __name__ == '__main__':
    if not os.path.exists(DB_PATH):
        from db_init import init_db
        init_db()
    app.run(host='0.0.0.0', port=5000, debug=True)
