from __future__ import annotations

from pathlib import Path

from jarvis_finance.imports.accounts_importer import import_accounts_csv
from jarvis_finance.storage.database import connect_memory
from jarvis_finance.storage.migrations import apply_migrations


def test_accounts_import_dry_run_does_not_write(tmp_path: Path) -> None:
    path = tmp_path / "accounts.csv"
    path.write_text(
        "platform_name,platform_type,account_name,account_type,currency,performance_included,is_health_reserve,notes\n"
        "Demo Broker,broker,Demo Depot,brokerage,CHF,1,0,Synthetic only\n",
        encoding="utf-8",
    )
    conn = connect_memory()
    apply_migrations(conn)

    result = import_accounts_csv(conn, path, commit=False, source_filename="accounts.csv")

    assert result.rows_total == 1
    assert result.rows_new == 1
    assert result.rows_existing == 0
    assert result.rows_failed == 0
    assert result.status == "dry_run_ok"
    assert conn.execute("SELECT COUNT(*) AS n FROM platforms").fetchone()["n"] == 0
    assert conn.execute("SELECT COUNT(*) AS n FROM import_sessions").fetchone()["n"] == 1


def test_accounts_import_commit_is_idempotent(tmp_path: Path) -> None:
    path = tmp_path / "accounts.csv"
    path.write_text(
        "platform_name,platform_type,account_name,account_type,currency,performance_included,is_health_reserve,notes\n"
        "Demo Broker,broker,Demo Depot,brokerage,CHF,1,0,Synthetic only\n",
        encoding="utf-8",
    )
    conn = connect_memory()
    apply_migrations(conn)

    first = import_accounts_csv(conn, path, commit=True, source_filename="accounts.csv")
    second = import_accounts_csv(conn, path, commit=True, source_filename="accounts.csv")

    assert first.rows_new == 1
    assert second.rows_new == 0
    assert second.rows_existing == 1
    assert conn.execute("SELECT COUNT(*) AS n FROM platforms").fetchone()["n"] == 1
    assert conn.execute("SELECT COUNT(*) AS n FROM accounts").fetchone()["n"] == 1
    assert conn.execute("SELECT COUNT(*) AS n FROM import_sessions").fetchone()["n"] == 2


def test_accounts_import_collects_validation_errors(tmp_path: Path) -> None:
    path = tmp_path / "bad_accounts.csv"
    path.write_text(
        "platform_name,platform_type,account_name,account_type,currency\n"
        ",broker,Demo Depot,brokerage,CHF\n",
        encoding="utf-8",
    )
    conn = connect_memory()
    apply_migrations(conn)

    result = import_accounts_csv(conn, path, commit=True, source_filename="bad_accounts.csv")

    assert result.rows_failed == 1
    assert result.status == "failed"
    assert "platform_name" in result.errors[0]
    assert conn.execute("SELECT COUNT(*) AS n FROM accounts").fetchone()["n"] == 0
