"""Локальный upload Cian cookies в tradein-postgres через SSH tunnel.

Не требует docker exec на проде. Требует:
  pip install "psycopg[binary]"
  SSH tunnel поднят к tradein-postgres (см. README рядом)
  Env: TRADEIN_DB_DSN, COOKIE_ENCRYPTION_KEY
"""
import json
import os
import sys

import psycopg

dsn = os.environ.get("TRADEIN_DB_DSN")
key = os.environ.get("COOKIE_ENCRYPTION_KEY")
if not dsn:
    sys.exit("FATAL: TRADEIN_DB_DSN env not set")
if not key:
    sys.exit("FATAL: COOKIE_ENCRYPTION_KEY env not set")

cookies = {
    "DMIR_AUTH": "<PASTE_FROM_BROWSER_DEVTOOLS>",
    "_CIAN_GK": "<PASTE_FROM_BROWSER_DEVTOOLS>",
    "_yasc": "<optional>",
    "_ym_isad": "<optional>",
    "uxfb_card_satisfaction": "<optional>",
}

# account_user_id — ваш Cian user ID (найти: DevTools → XHR → /v1/get-my-id/ → userId).
# Используется как ключ в cian_session_cookies. Для локального backfill
# достаточно любого уникального числа (например ваш реальный Cian userId).
ACCOUNT_USER_ID = 999999999  # TODO: замените на реальный Cian userId

with psycopg.connect(dsn) as conn:
    with conn.cursor() as cur:
        cur.execute("""
            INSERT INTO cian_session_cookies (
                account_user_id,
                cookies_encrypted,
                expires_at_estimate,
                uploaded_at,
                notes
            ) VALUES (
                CAST(%s AS bigint),
                pgp_sym_encrypt(%s, %s),
                NOW() + INTERVAL '30 days',
                NOW(),
                'manual local upload via SSH tunnel'
            )
            ON CONFLICT (account_user_id) DO UPDATE SET
                cookies_encrypted    = EXCLUDED.cookies_encrypted,
                expires_at_estimate  = EXCLUDED.expires_at_estimate,
                uploaded_at          = NOW(),
                last_invalid_at      = NULL
        """, (ACCOUNT_USER_ID, json.dumps(cookies), key))
        conn.commit()
        cur.execute(
            "SELECT account_user_id, uploaded_at, expires_at_estimate, "
            "octet_length(cookies_encrypted) AS enc_bytes "
            "FROM cian_session_cookies WHERE account_user_id = CAST(%s AS bigint)",
            (ACCOUNT_USER_ID,),
        )
        row = cur.fetchone()
        print(f"OK saved: user_id={row[0]} uploaded={row[1]} expires={row[2]} "
              f"enc_bytes={row[3]}")
