import os, sqlite3, time
from pathlib import Path
from typing import Optional, Dict

DEFAULT_DB_PATH = os.path.join(str(Path.home()), ".umarise", "ledger.db")

class ReconciliationLedger:
    def __init__(self, db_path=None):
        self._db_path = db_path or DEFAULT_DB_PATH
        os.makedirs(os.path.dirname(self._db_path), exist_ok=True)
        self._init_db()
    def _connect(self):
        conn = sqlite3.connect(self._db_path)
        conn.row_factory = sqlite3.Row
        return conn
    def _init_db(self):
        with self._connect() as conn:
            conn.execute("""CREATE TABLE IF NOT EXISTS anchor_ledger (
                id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL,
                file_path TEXT NOT NULL, hash TEXT NOT NULL, origin_id TEXT,
                proof_status TEXT DEFAULT 'pending', created_at REAL NOT NULL,
                updated_at REAL NOT NULL, error TEXT)""")
    def record(self, source, file_path, file_hash, origin_id=None, proof_status="pending", error=None):
        now = time.time()
        with self._connect() as conn:
            cur = conn.execute(
                "INSERT INTO anchor_ledger (source,file_path,hash,origin_id,proof_status,created_at,updated_at,error) VALUES (?,?,?,?,?,?,?,?)",
                (source, file_path, file_hash, origin_id, proof_status, now, now, error))
            return cur.lastrowid
    def record_failure(self, source, file_path, file_hash, error):
        return self.record(source, file_path, file_hash, proof_status="failed", error=error)
    def stats(self):
        with self._connect() as conn:
            row = conn.execute("SELECT COUNT(*) as total FROM anchor_ledger").fetchone()
            return dict(row)
    @property
    def db_path(self): return self._db_path
