from __future__ import annotations
from pathlib import Path
from sqlite3 import Connection
from jarvis_finance.crypto.wallets import create_wallet
from .common import ImportResult, clean, create_import_session, require_text, source_hash
from .dry_run import read_csv_rows
from .row_hash import compute_row_hash

REQUIRED_COLUMNS={"wallet_name","wallet_type"}

def import_crypto_wallets_csv(conn:Connection,path:str|Path,*,commit:bool,source_filename:str|None=None)->ImportResult:
    rows, errors=read_csv_rows(path, REQUIRED_COLUMNS); source_filename=source_filename or Path(path).name
    new=existing=0; validated=[]; seen=set()
    for line,row in enumerate(rows,start=2):
        try:
            rh=compute_row_hash(row)
            if rh in seen: raise ValueError(f"line {line}: duplicate row hash in source file")
            seen.add(rh); name=require_text(row,"wallet_name",line); typ=require_text(row,"wallet_type",line)
            exists=conn.execute("SELECT 1 FROM crypto_wallets WHERE wallet_name=?",(name,)).fetchone() is not None
            existing += 1 if exists else 0; new += 0 if exists else 1
            validated.append((name,typ,clean(row.get('platform_provider')) or None,clean(row.get('network_chain')) or None,clean(row.get('notes')) or None))
        except ValueError as exc: errors.append(str(exc))
    status='failed' if errors else ('committed' if commit else 'dry_run_ok')
    if commit and not errors:
        for name,typ,provider,chain,notes in validated:
            if conn.execute("SELECT 1 FROM crypto_wallets WHERE wallet_name=?",(name,)).fetchone(): continue
            create_wallet(conn,wallet_name=name,wallet_type=typ,platform_provider=provider,network_chain=chain,notes=notes)
    sid=create_import_session(conn,import_type='crypto_wallets',source_filename=source_filename,file_hash=source_hash(path),status=status,rows_total=len(rows),rows_imported=new if commit and not errors else 0,rows_failed=len(errors),errors=errors,notes='dry run' if not commit else None)
    return ImportResult(sid,'crypto_wallets',status,len(rows),new if not errors else 0,existing,len(errors),errors)
