import os, requests
from datetime import datetime, timedelta, timezone
from dotenv import load_dotenv
from t_tech.invest import Client

os.environ['SSL_CERT_FILE'] = '/etc/ssl/certs/ca-certificates.crt'
os.environ['GRPC_DEFAULT_SSL_ROOTS_FILE_PATH'] = '/etc/ssl/certs/ca-certificates.crt'

load_dotenv("/root/sber_bot/tok.env")
TOKEN = os.getenv("TINKOFF_TOKEN")
ACC_ID = os.getenv("ACCOUNT_ID")

def q_to_f(q): return q.units + q.nano/1e9 if q else 0

with Client(TOKEN, target="invest-public-api.tbank.ru:443") as client:
    from_date = datetime.now(timezone.utc) - timedelta(days=1)
    to_date = datetime.now(timezone.utc)
    
    print(f"\n--- РЕАЛЬНЫЕ СДЕЛКИ ЗА 24 ЧАСА (Счет {ACC_ID}) ---")
    ops = client.operations.get_operations(account_id=ACC_ID, from_=from_date, to=to_date).operations
    
    for o in ops:
        if o.operation_type.name in ['OPERATION_TYPE_BUY', 'OPERATION_TYPE_SELL']:
            print(f"{o.date.strftime('%H:%M:%S')} | {o.type} | {q_to_f(o.price)} руб. | {o.quantity} шт. | Итог: {q_to_f(o.payment)} руб.")
