from __future__ import annotations

from pathlib import Path

from jarvis_finance.imports.accounts_importer import import_accounts_csv
from jarvis_finance.services.performance_scope import set_performance_scope_classification
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 performance_included FROM accounts").fetchone()[0] == 0
    assert conn.execute("SELECT COUNT(*) FROM performance_scope_classifications").fetchone()[0] == 0
    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


def test_household_account_import_cannot_change_an_existing_performance_scope(tmp_path: Path) -> None:
    path = tmp_path / "household_accounts.csv"
    path.write_text(
        "platform_name,platform_type,account_name,account_type,currency,performance_included,is_health_reserve,notes\n"
        "Household Bank,bank,Daily Cash,cash,CHF,1,0,Synthetic only\n",
        encoding="utf-8",
    )
    conn = connect_memory()
    apply_migrations(conn)
    conn.execute(
        "INSERT INTO platforms(platform_id,name,platform_type,created_at) VALUES('pf','PostFinance','broker','2026-01-01')"
    )
    conn.execute(
        """INSERT INTO accounts(account_id,platform_id,account_name,account_type,currency,
             performance_included,created_at)
           VALUES('pf-depot','pf','PostFinance E-Trading','brokerage','CHF',0,'2026-01-01')"""
    )
    set_performance_scope_classification(
        conn,
        account_id="pf-depot",
        included=True,
        classification_role="postfinance_etrading_depot",
        source="test",
        note="approved synthetic role",
        classified_at="2026-01-01T00:00:00Z",
    )
    before = tuple(conn.execute(
        """SELECT a.performance_included,c.included,c.classification_role,c.audit_id
           FROM accounts a JOIN performance_scope_classifications c USING(account_id)
           WHERE a.account_id='pf-depot'"""
    ).fetchone())

    result = import_accounts_csv(conn, path, commit=True, source_filename=path.name)

    assert result.status == "committed"
    assert tuple(conn.execute(
        """SELECT a.performance_included,c.included,c.classification_role,c.audit_id
           FROM accounts a JOIN performance_scope_classifications c USING(account_id)
           WHERE a.account_id='pf-depot'"""
    ).fetchone()) == before
    household = conn.execute(
        """SELECT performance_included FROM accounts
           WHERE account_name='Daily Cash'"""
    ).fetchone()
    assert household[0] == 0
    assert conn.execute(
        """SELECT COUNT(*) FROM performance_scope_classifications c
           JOIN accounts a USING(account_id) WHERE a.account_name='Daily Cash'"""
    ).fetchone()[0] == 0
