import os
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")

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:
    # Загружаем тикеры
    shares = client.instruments.shares().instruments
    ticker_map = {s.uid: s.ticker for s in shares}
    figi_map = {s.figi: s.ticker for s in shares}

    accounts = client.users.get_accounts().accounts
    
    print(f"{'Дата (MSK)':<15} | {'Счет':<12} | {'Тикер':<6} | {'Тип':<5} | {'Цена':<8} | {'Сумма':<10}")
    print("-" * 80)

    for acc in accounts:
        ops = client.operations.get_operations(
            account_id=acc.id,
            from_=datetime.now(timezone.utc) - timedelta(days=10),
            to=datetime.now(timezone.utc)
        ).operations

        for o in ops:
            if "TYPE_BUY" in o.operation_type.name or "TYPE_SELL" in o.operation_type.name:
                # Определяем тикер
                t = ticker_map.get(o.instrument_uid) or figi_map.get(o.figi) or "N/A"
                date = o.date.astimezone(timezone(timedelta(hours=3))).strftime("%d.%m %H:%M")
                op_type = "BUY" if "BUY" in o.operation_type.name else "SELL"
                price = q_to_f(o.price)
                payment = q_to_f(o.payment)
                
                print(f"{date:<15} | {acc.name[:12]:<12} | {t:<6} | {op_type:<5} | {price:<8.2f} | {payment:<10.2f}")
