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

# Константы для поиска
TATN_TICKER = "TATN"
TATN_UID = "88468f6c-c67a-4fb4-a006-53eed803883c"

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
    figi_to_ticker = {s.figi: s.ticker for s in shares}
    uid_to_ticker = {s.uid: s.ticker for s in shares}

    accounts = client.users.get_accounts().accounts
    
    print(f"\n--- ПОИСК СДЕЛОК ПО ТАТНЕФТИ (TATN) ---")
    print(f"{'Дата (MSK)':<15} | {'Счет':<12} | {'Тип':<5} | {'Цена':<8} | {'Кол':<4} | {'Сумма':<10}")
    print("-" * 75)

    for acc in accounts:
        # Запрашиваем ВСЕ операции без фильтра по FIGI на сервере
        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:
            # Проверяем, Татнефть ли это (по FIGI или UID)
            ticker = figi_to_ticker.get(o.figi) or uid_to_ticker.get(o.instrument_uid)
            if ticker == TATN_TICKER:
                if "TYPE_BUY" in o.operation_type.name or "TYPE_SELL" in o.operation_type.name:
                    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} | {op_type:<5} | {price:<8.2f} | {int(o.quantity):<4} | {payment:<10.2f}")
