"""銀行明細テーブルを直接作成する"""
import paramiko

HOST = "192.168.0.61"
USER = "root"
PASS = "59911784"

SQL = """
CREATE TABLE IF NOT EXISTS bank_statement_rows (
    id              SERIAL PRIMARY KEY,
    tx_date         DATE        NOT NULL,
    description     TEXT        NOT NULL DEFAULT '',
    debit           BIGINT      NOT NULL DEFAULT 0,
    credit          BIGINT      NOT NULL DEFAULT 0,
    balance         BIGINT,
    memo            TEXT        NOT NULL DEFAULT '',
    bank_name       TEXT        NOT NULL DEFAULT '',
    import_batch_id TEXT        NOT NULL,
    row_hash        TEXT        NOT NULL,
    imported_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT uq_bank_stmt_hash UNIQUE (row_hash)
);
CREATE INDEX IF NOT EXISTS idx_bank_stmt_date  ON bank_statement_rows (tx_date);
CREATE INDEX IF NOT EXISTS idx_bank_stmt_batch ON bank_statement_rows (import_batch_id);
"""

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASS, timeout=15)

cmd = f"""docker exec njts-accounting-backend python -c "
import os, psycopg
conn = psycopg.connect(host=os.getenv('DB_HOST'), port=os.getenv('DB_PORT'), dbname=os.getenv('DB_NAME'), user=os.getenv('DB_USER'), password=os.getenv('DB_PASSWORD'))
cur = conn.cursor()
cur.execute(\\\"\\\"\\\"
CREATE TABLE IF NOT EXISTS bank_statement_rows (
    id              SERIAL PRIMARY KEY,
    tx_date         DATE        NOT NULL,
    description     TEXT        NOT NULL DEFAULT '',
    debit           BIGINT      NOT NULL DEFAULT 0,
    credit          BIGINT      NOT NULL DEFAULT 0,
    balance         BIGINT,
    memo            TEXT        NOT NULL DEFAULT '',
    bank_name       TEXT        NOT NULL DEFAULT '',
    import_batch_id TEXT        NOT NULL,
    row_hash        TEXT        NOT NULL,
    imported_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT uq_bank_stmt_hash UNIQUE (row_hash)
)
\\\"\\\"\\\")
cur.execute('CREATE INDEX IF NOT EXISTS idx_bank_stmt_date  ON bank_statement_rows (tx_date)')
cur.execute('CREATE INDEX IF NOT EXISTS idx_bank_stmt_batch ON bank_statement_rows (import_batch_id)')
conn.commit()
print('テーブル作成完了')
conn.close()
"
"""

_, o, e = client.exec_command(cmd, timeout=30)
print(o.read().decode())
err = e.read().decode()
if err: print("STDERR:", err)
client.close()
