import requests
import sqlite3
import os
import uuid
import threading
import time
from datetime import datetime


def _writable_dir() -> str:
    """Return the app's private writable folder on Android, or CWD on desktop."""
    if 'ANDROID_ARGUMENT' in os.environ or 'ANDROID_PRIVATE' in os.environ:
        path = os.environ.get('ANDROID_PRIVATE') or os.environ.get('ANDROID_APP_PATH', '.')
        try:
            os.makedirs(path, exist_ok=True)
        except Exception:
            pass
        return path
    return os.path.dirname(os.path.abspath(__file__))


# Use the same shared database location the engine writes to.
DB_PATH = os.path.join(_writable_dir(), 'adaptive_hedge_trades.db')
REPORT_URL = 'https://nirdainstitute.org/api/report.php'  # CHANGE TO YOUR ENDPOINT


def get_user_id():
    uid_file = os.path.join(_writable_dir(), 'user_id.txt')
    if os.path.exists(uid_file):
        with open(uid_file, 'r') as f:
            return f.read().strip()
    else:
        new_id = str(uuid.uuid4())
        try:
            with open(uid_file, 'w') as f:
                f.write(new_id)
        except Exception:
            pass
        return new_id


USER_ID = get_user_id()


def send_trade_report(trade_data):
    payload = {
        'user_id': USER_ID,
        'timestamp': datetime.now().isoformat(),
        'type': 'trade',
        'data': trade_data
    }
    try:
        r = requests.post(REPORT_URL, json=payload, timeout=10)
        return r.ok
    except Exception:
        return False


def send_daily_summary():
    try:
        conn = sqlite3.connect(DB_PATH)
        c = conn.cursor()
        today = datetime.now().date().isoformat()
        c.execute("""
            SELECT COUNT(*), SUM(net_pnl), SUM(gross_pnl)
            FROM trades 
            WHERE exit_time IS NOT NULL AND date(exit_time) = ?
        """, (today,))
        count, net, gross = c.fetchone()
        c.execute("""
            SELECT net_pnl FROM trades 
            WHERE exit_time IS NOT NULL AND date(exit_time) = ? AND net_pnl > 0
        """, (today,))
        wins = c.fetchall()
        total_profit = sum(pnl for (pnl,) in wins if pnl)
        developer_fee = total_profit * 0.01
        conn.close()
        payload = {
            'user_id': USER_ID,
            'timestamp': datetime.now().isoformat(),
            'type': 'daily_summary',
            'data': {
                'trades': count or 0,
                'net_pnl': net or 0.0,
                'gross_pnl': gross or 0.0,
                'total_profit': total_profit,
                'developer_fee': developer_fee,
                'date': today
            }
        }
        r = requests.post(REPORT_URL, json=payload, timeout=10)
        return r.ok
    except Exception as e:
        # Silent log to a file — print() is invisible on Android.
        try:
            with open(os.path.join(_writable_dir(), 'reporter_error.log'), 'a') as f:
                f.write(f"{datetime.now().isoformat()} | Report error: {e}\n")
        except Exception:
            pass
        return False


def run_reporter():
    last_report_date = None
    while True:
        today = datetime.now().date()
        if last_report_date != today:
            send_daily_summary()
            last_report_date = today
        time.sleep(3600)


def start_reporter():
    thread = threading.Thread(target=run_reporter, daemon=True)
    thread.start()
