import os
import tempfile
import asyncio
import threading
from datetime import datetime
from flask import Flask, jsonify, request, render_template, send_file
from telegram import Update
from bot import setup_application
from database import (
    get_stok_harian_detail,
    is_shift_closed,
    close_shift,
    get_kategori_all,
    add_kategori,
    add_barang,
    get_laporan_khusus,
    edit_barang_stok,
    get_trend_data,
    get_audit_log,
    delete_barang
)
from report_generator import generate_pdf_report, generate_excel_report

app = Flask(__name__)

# Mengatur agar Flask mencari template di direktori 'templates' di tingkat yang sama
TEMPLATE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
app.template_folder = TEMPLATE_DIR

# --- WEBHOOK LOGIC ---
telegram_app = None
telegram_thread = None
bot_pid = None

app_ready_event = threading.Event()

def start_telegram_bot():
    global telegram_app, bot_loop, bot_pid
    try:
        bot_pid = os.getpid()
        bot_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(bot_loop)
        telegram_app = setup_application()
        if telegram_app:
            bot_loop.run_until_complete(telegram_app.initialize())
            # Opsional: jalankan start() jika dibutuhkan oleh beberapa fitur
            bot_loop.run_until_complete(telegram_app.start())
            app_ready_event.set()
            bot_loop.run_forever()
    except Exception as e:
        import traceback
        with open("telegram_thread_error.log", "w") as f:
            f.write(traceback.format_exc())
            f.write(str(e))

def ensure_telegram_thread():
    global telegram_thread, bot_pid
    current_pid = os.getpid()
    if telegram_thread is None or not telegram_thread.is_alive() or bot_pid != current_pid:
        app_ready_event.clear()
        telegram_thread = threading.Thread(target=start_telegram_bot, daemon=True)
        telegram_thread.start()
    app_ready_event.wait(timeout=10)

@app.route('/webhook', methods=['POST'])
def webhook():
    """Endpoint untuk menerima update dari Telegram (Webhook)."""
    ensure_telegram_thread()
    try:
        req_json = request.get_json(force=True)
        if telegram_app and bot_loop:
            update = Update.de_json(req_json, telegram_app.bot)
            async def reload_and_process():
                from bot import reload_conversations_from_db
                await reload_conversations_from_db(telegram_app)
                await telegram_app.process_update(update)
                await telegram_app.update_persistence()
            future = asyncio.run_coroutine_threadsafe(reload_and_process(), bot_loop)
            try:
                future.result(timeout=10)
            except Exception as fe:
                with open("telegram_thread_error.log", "a") as f:
                    f.write(f"Future Error: {fe}\n")
        return "OK", 200
    except Exception as e:
        print(f"Error handling webhook: {e}")
        import traceback
        traceback.print_exc()
        return "Error", 500

@app.route('/set_webhook', methods=['GET'])
def set_webhook():
    """Set Webhook Telegram. Akses via /set_webhook?url=https://domainanda.com/webhook"""
    webhook_url = request.args.get('url')
    if not webhook_url:
        return "Gagal: Harap sertakan parameter ?url=https://domainanda.com/webhook", 400
        
    ensure_telegram_thread()
    
    # Tunggu maksimal 5 detik jika bot sedang inisialisasi
    import time
    for _ in range(10):
        if telegram_app and bot_loop:
            break
        time.sleep(0.5)
        
    try:
        if telegram_app and bot_loop:
            asyncio.run_coroutine_threadsafe(
                telegram_app.bot.set_webhook(url=webhook_url), bot_loop
            )
            return jsonify({"status": "success", "url": webhook_url}), 200
        return jsonify({"status": "error", "message": "Bot belum siap."}), 500
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500
# --- END WEBHOOK LOGIC ---

@app.route('/debug/test_connect')
def debug_test_connect():
    import urllib.request
    import urllib.error
    import httpx
    import asyncio
    
    urllib_status = "Not tested"
    try:
        response = urllib.request.urlopen("https://api.telegram.org", timeout=10)
        urllib_status = f"Success (urllib)! Status code: {response.status}"
    except urllib.error.URLError as e:
        urllib_status = f"URL Error (urllib): {e.reason}"
    except Exception as e:
        urllib_status = f"Error (urllib): {str(e)}"
        
    httpx_status = "Not tested"
    try:
        async def test_httpx():
            async with httpx.AsyncClient(timeout=10) as client:
                res = await client.get("https://api.telegram.org")
                return f"Success (httpx)! Status code: {res.status_code}"
        httpx_status = asyncio.run(test_httpx())
    except Exception as e:
        httpx_status = f"Error (httpx): {str(e)}"
        
    return f"Urllib: {urllib_status}<br>Httpx: {httpx_status}"

@app.route('/')
def index():
    """Menyajikan halaman dashboard utama."""
    return render_template('index.html')

@app.route('/api/summary', methods=['GET'])
def get_summary():
    """Mendapatkan ringkasan metrik keuangan dan operasional untuk tanggal tertentu."""
    tanggal = request.args.get('tanggal')
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
        
    try:
        data = get_stok_harian_detail(tanggal)
        kategori = request.args.get('kategori')
        if kategori:
            data = [d for d in data if str(d['nama_kategori']).lower() == str(kategori).lower()]
        
        
        total_omset = 0
        total_modal = 0
        total_laba = 0
        total_laku = 0
        
        for item in data:
            # Hitung dynamic calculations
            total_jual = item['jual'] * item['harga_jual']
            total_beli = item['beli'] * item['harga_beli']
            laba = total_jual - total_beli
            
            total_omset += total_jual
            total_modal += total_beli
            total_laba += laba
            total_laku += item['jual']
            
        status_shift = "CLOSED" if is_shift_closed(tanggal) else "OPEN"
        
        # Tambahan data chart untuk kategori
        kategori_data = {}
        for item in data:
            cat_name = item['nama_kategori']
            total_jual = item['jual'] * item['harga_jual']
            kategori_data[cat_name] = kategori_data.get(cat_name, 0) + total_jual
            
        # Tambahan data chart untuk top 5 barang terlaris
        sorted_barang = sorted(data, key=lambda x: x['jual'], reverse=True)
        top_barang = []
        for item in sorted_barang[:5]:
            if item['jual'] > 0:
                top_barang.append({
                    "nama": item['nama_barang'],
                    "jual": item['jual']
                })
        
        # Fetch Indomie & Gorengan Data
        laporan_khusus = get_laporan_khusus(tanggal)
        total_modal_khusus = sum(b['harga_beli'] for b in laporan_khusus['bahan'])
        total_omset_khusus = sum(m['total'] for m in laporan_khusus['menu'])
        total_laba_khusus = total_omset_khusus - total_modal_khusus
        
        # Include in main summary if category not filtered or filtered to Indomie
        if not kategori or str(kategori).lower() == 'indomie & gorengan':
            total_omset += total_omset_khusus
            total_modal += total_modal_khusus
            total_laba += total_laba_khusus
            # Let's add special chart data
            if total_omset_khusus > 0:
                kategori_data['Indomie & Gorengan'] = total_omset_khusus
        
        return jsonify({
            "status": "success",
            "tanggal": tanggal,
            "summary": {
                "total_omset": total_omset,
                "total_modal": total_modal,
                "total_laba": total_laba,
                "total_laku": total_laku,
                "status_shift": status_shift
            },
            "kategori_chart": {
                "labels": list(kategori_data.keys()),
                "data": list(kategori_data.values())
            },
            "top_barang_chart": {
                "labels": [b['nama'] for b in top_barang],
                "data": [b['jual'] for b in top_barang]
            }
        })
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/stok', methods=['GET'])
def get_stok():
    """Mendapatkan rincian tabel stok harian lengkap untuk tanggal tertentu."""
    tanggal = request.args.get('tanggal')
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
        
    try:
        data = get_stok_harian_detail(tanggal)
        kategori = request.args.get('kategori')
        if kategori:
            data = [d for d in data if str(d['nama_kategori']).lower() == str(kategori).lower()]
        
        result = []
        for idx, item in enumerate(data, 1):
            jumlah = item['sisa_h1'] + item['beli']
            sisa = jumlah - item['jual']
            total_jual = item['jual'] * item['harga_jual']
            total_beli = item['beli'] * item['harga_beli']
            laba = total_jual - total_beli
            
            result.append({
                "no": idx,
                "nama_barang": item['nama_barang'],
                "nama_kategori": item['nama_kategori'],
                "id_kategori": item['id_kategori'],
                "sisa_h1": item['sisa_h1'],
                "beli": item['beli'],
                "jumlah": jumlah,
                "jual": item['jual'],
                "sisa": sisa,
                "harga_beli": item['harga_beli'],
                "harga_jual": item['harga_jual'],
                "total_jual": total_jual,
                "total_beli": total_beli,
                "laba": laba,
                "barang_id": item['barang_id']
            })
        return jsonify({"status": "success", "tanggal": tanggal, "data": result})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/stok_khusus', methods=['GET'])
def get_stok_khusus():
    """Mendapatkan rincian tabel Indomie & Gorengan untuk tanggal tertentu."""
    tanggal = request.args.get('tanggal')
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
    
    try:
        data = get_laporan_khusus(tanggal)
        return jsonify({"status": "success", "tanggal": tanggal, "data": data})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/trend', methods=['GET'])
def api_trend():
    """Mendapatkan data tren penjualan (omset dan laba) 30 hari terakhir."""
    try:
        data = get_trend_data(30)
        return jsonify({"status": "success", "data": data})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/audit', methods=['GET'])
def api_audit():
    """Mendapatkan log transaksi / audit trail untuk tanggal tertentu."""
    tanggal = request.args.get('tanggal')
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
    try:
        data = get_audit_log(tanggal)
        return jsonify({"status": "success", "tanggal": tanggal, "data": data})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/keuangan', methods=['GET'])
def get_keuangan():
    tanggal = request.args.get('tanggal')
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
    try:
        from database import get_transaksi_keuangan_by_tanggal
        data = get_transaksi_keuangan_by_tanggal(tanggal)
        return jsonify({"status": "success", "tanggal": tanggal, "data": data})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/keuangan', methods=['POST'])
def add_keuangan():
    req_data = request.get_json() or {}
    tanggal = req_data.get('tanggal')
    jenis = req_data.get('jenis')
    kategori = req_data.get('kategori')
    keterangan = req_data.get('keterangan', '')
    nominal = req_data.get('nominal')
    
    if not (tanggal and jenis and kategori and nominal):
        return jsonify({"status": "error", "message": "Data tidak lengkap."}), 400
        
    try:
        from database import add_transaksi_keuangan, add_audit_log
        add_transaksi_keuangan(tanggal, jenis, kategori, keterangan, int(nominal))
        
        # Log to audit trail
        waktu = datetime.now().strftime("%H:%M:%S")
        add_audit_log(tanggal, waktu, "Website", 0, f"Keuangan ({jenis})", f"Kategori: {kategori}, Ket: {keterangan}, Nominal: {nominal}")
        
        return jsonify({"status": "success", "message": "Transaksi keuangan berhasil disimpan."})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/keuangan/delete', methods=['POST'])
def delete_keuangan():
    req_data = request.get_json() or {}
    id_transaksi = req_data.get('id')
    tanggal = req_data.get('tanggal')
    
    if not id_transaksi:
        return jsonify({"status": "error", "message": "ID transaksi diperlukan."}), 400
        
    try:
        from database import delete_transaksi_keuangan, add_audit_log
        delete_transaksi_keuangan(int(id_transaksi))
        
        # Log to audit trail
        waktu = datetime.now().strftime("%H:%M:%S")
        add_audit_log(tanggal, waktu, "Website", 0, "Hapus Keuangan", f"Menghapus transaksi keuangan ID: {id_transaksi}")
        
        return jsonify({"status": "success", "message": "Transaksi keuangan berhasil dihapus."})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/keuangan/reset', methods=['POST'])
def reset_keuangan():
    req_data = request.get_json() or {}
    tanggal = req_data.get('tanggal')
    
    if not tanggal:
        return jsonify({"status": "error", "message": "Tanggal diperlukan."}), 400
        
    try:
        from database import reset_transaksi_keuangan, add_audit_log
        reset_transaksi_keuangan(tanggal)
        
        # Log to audit trail
        waktu = datetime.now().strftime("%H:%M:%S")
        add_audit_log(tanggal, waktu, "Website", 0, "Reset Keuangan", f"Reset semua transaksi keuangan tanggal {tanggal}")
        
        return jsonify({"status": "success", "message": "Semua transaksi keuangan hari ini berhasil di-reset."})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/report/pdf_keuangan', methods=['GET'])
def download_pdf_keuangan():
    tanggal = request.args.get('tanggal')
    if not tanggal:
        return "Tanggal diperlukan.", 400
        
    try:
        from report_generator import generate_pdf_keuangan
        pdf_path = f"laporan_keuangan_{tanggal}.pdf"
        generate_pdf_keuangan(tanggal, pdf_path)
        return send_file(pdf_path, as_attachment=True, download_name=f"Laporan_Keuangan_{tanggal}.pdf")
    except Exception as e:
        return str(e), 500

@app.route('/api/tutup_shift', methods=['POST'])
def post_tutup_shift():
    """Menutup shift untuk tanggal tertentu."""
    req_data = request.get_json() or {}
    tanggal = req_data.get('tanggal')
    
    if not tanggal:
        return jsonify({"status": "error", "message": "Tanggal diperlukan."}), 400
        
    try:
        success, message = close_shift(tanggal)
        if success:
            return jsonify({"status": "success", "message": message})
        else:
            return jsonify({"status": "fail", "message": message}), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/edit_barang', methods=['POST'])
def edit_barang_api():
    """Mengupdate detail barang dan stoknya secara langsung (Inline Edit)."""
    req_data = request.get_json() or {}
    tanggal = req_data.get('tanggal')
    id_barang = req_data.get('barang_id')
    
    if not tanggal or not id_barang:
        return jsonify({"status": "error", "message": "Tanggal dan barang_id diperlukan."}), 400
        
    try:
        edit_barang_stok(
            tanggal=tanggal,
            id_barang=id_barang,
            nama_barang=req_data.get('nama_barang'),
            harga_beli=req_data.get('harga_beli'),
            harga_jual=req_data.get('harga_jual'),
            sisa_h1=req_data.get('sisa_h1'),
            beli=req_data.get('beli'),
            jual=req_data.get('jual'),
            id_kategori=req_data.get('id_kategori')
        )
        return jsonify({"status": "success", "message": "Barang dan stok berhasil diperbarui."})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/delete_barang', methods=['POST'])
def delete_barang_api():
    """Menghapus master barang secara permanen."""
    req_data = request.get_json() or {}
    id_barang = req_data.get('barang_id')
    
    if not id_barang:
        return jsonify({"status": "error", "message": "barang_id diperlukan."}), 400
        
    try:
        success = delete_barang(id_barang)
        if success:
            return jsonify({"status": "success", "message": "Barang berhasil dihapus."})
        else:
            return jsonify({"status": "error", "message": "Barang tidak ditemukan."}), 404
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/kategori', methods=['GET'])
def get_kategori():
    """Mendapatkan daftar semua kategori untuk dropdown."""
    try:
        data = get_kategori_all()
        return jsonify({"status": "success", "data": data})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/kategori', methods=['POST'])
def post_kategori():
    """Menambahkan kategori baru."""
    req_data = request.get_json() or {}
    nama_kategori = req_data.get('nama_kategori')
    
    if not nama_kategori:
        return jsonify({"status": "error", "message": "Nama kategori harus diisi."}), 400
        
    try:
        new_id = add_kategori(nama_kategori)
        if new_id:
            return jsonify({"status": "success", "message": f"Kategori '{nama_kategori}' berhasil ditambahkan."})
        else:
            return jsonify({"status": "fail", "message": "Gagal menambahkan kategori. Mungkin sudah terdaftar."}), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/barang', methods=['POST'])
def post_barang():
    """Menambahkan master barang baru dan menginisialisasi stok awalnya."""
    req_data = request.get_json() or {}
    nama_barang = req_data.get('nama_barang')
    id_kategori = req_data.get('id_kategori')
    harga_beli = req_data.get('harga_beli')
    harga_jual = req_data.get('harga_jual')
    qty = req_data.get('qty', 0)
    tanggal = req_data.get('tanggal')
    
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
        
    if not all([nama_barang, id_kategori, harga_beli is not None, harga_jual is not None]):
        return jsonify({"status": "error", "message": "Semua field harus diisi."}), 400
        
    try:
        new_id = add_barang(id_kategori, nama_barang, harga_beli, harga_jual)
        if new_id:
            # Inisialisasi stok harian untuk barang baru ini di tanggal terpilih
            from database import init_stok_harian_untuk_tanggal, get_db_connection
            init_stok_harian_untuk_tanggal(tanggal)
            # Set stok awal (sisa_h1) sesuai qty input
            if qty > 0:
                with get_db_connection() as conn:
                    conn.execute(
                        "UPDATE stok_harian SET sisa_h1 = ? WHERE tanggal = ? AND id_barang = ?;",
                        (int(qty), tanggal, new_id)
                    )
                    conn.commit()
            return jsonify({"status": "success", "message": f"Barang '{nama_barang}' berhasil ditambahkan dengan stok awal {qty}."})
        else:
            return jsonify({"status": "fail", "message": "Gagal menambahkan barang. Mungkin format salah."}), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/report/pdf', methods=['GET'])
def download_pdf():
    """Mengunduh laporan PDF untuk tanggal tertentu."""
    tanggal = request.args.get('tanggal')
    kategori = request.args.get('kategori')
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
        
    # Buat file temporary untuk menyimpan PDF
    temp_dir = tempfile.gettempdir()
    pdf_path = os.path.join(temp_dir, f"temp_laporan_{tanggal}.pdf")
    
    try:
        generate_pdf_report(tanggal, pdf_path, filter_kategori=kategori)
        return send_file(
            pdf_path,
            as_attachment=True,
            download_name=f"laporan_kantin_{tanggal}.pdf",
            mimetype="application/pdf"
        )
    except Exception as e:
        return f"Gagal membuat laporan PDF: {str(e)}", 500

@app.route('/report/excel', methods=['GET'])
def download_excel():
    """Mengunduh laporan Excel untuk tanggal tertentu."""
    tanggal = request.args.get('tanggal')
    kategori = request.args.get('kategori')
    if not tanggal:
        tanggal = datetime.now().strftime("%Y-%m-%d")
        
    # Buat file temporary untuk menyimpan Excel
    temp_dir = tempfile.gettempdir()
    excel_path = os.path.join(temp_dir, f"temp_laporan_{tanggal}.xlsx")
    
    try:
        generate_excel_report(tanggal, excel_path, filter_kategori=kategori)
        return send_file(
            excel_path,
            as_attachment=True,
            download_name=f"laporan_kantin_{tanggal}.xlsx",
            mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
    except Exception as e:
        return f"Gagal membuat laporan Excel: {str(e)}", 500

if __name__ == '__main__':
    # Pastikan database terinisialisasi
    from database import init_db
    init_db()
    
    print("Menjalankan Web Dashboard di http://127.0.0.1:5000")
    app.run(host='127.0.0.1', port=5000, debug=True)
