"""
main.py — The orchestrator. Run this to process a batch end-to-end:
  raw transactions -> Claude classify -> build XML -> push to Tally.

Usage:
  python main.py                 # runs the built-in sample batch
  python main.py entries.csv     # classify + push rows from a CSV
"""
import csv
import sys

from ai.claude_processor import classify_transactions
from builder.xml_generator import build_voucher_xml
from builder.validator import validate_entries
from push.tally_importer import push_to_tally

# ── Sample raw transactions (from bank CSV or manual) ──
SAMPLE = [
    {"date": "2025-06-01", "description": "DEWA electricity bill",       "amount": -850.00},
    {"date": "2025-06-03", "description": "Client fee received - Khadlaj", "amount": 15000.00},
    {"date": "2025-06-10", "description": "Carrefour groceries",          "amount": -320.00},
    {"date": "2025-06-15", "description": "ADCB transfer to Mashreq",      "amount": -5000.00},
]


def load_csv(path: str) -> list:
    """Load a simple bank CSV with columns: date, description, amount."""
    rows = []
    with open(path, newline="", encoding="utf-8-sig") as f:
        for r in csv.DictReader(f):
            rows.append({
                "date": r.get("date") or r.get("Date", ""),
                "description": r.get("description") or r.get("Description", ""),
                "amount": float(r.get("amount") or r.get("Amount") or 0),
            })
    return rows


def run_pipeline(transactions: list) -> dict:
    print("\n[1] Sending to Claude AI for classification...")
    entries = classify_transactions(transactions)
    print(f"    -> {len(entries)} entries classified.")

    problems = validate_entries(entries)
    if problems:
        print("    ! Validation problems found:")
        for p in problems:
            print("      -", p)
        return {"success": False, "message": "validation failed", "imported": 0}

    print("\n[2] Building Tally XML...")
    xml_str = build_voucher_xml(entries)
    print("    -> XML built.")

    print("\n[3] Pushing to TallyPrime on Port 9000...")
    result = push_to_tally(xml_str)

    if result["success"]:
        print(f"    -> SUCCESS: {result['message']}")
    else:
        print(f"    -> ERROR: {result['message']}")

    return result


if __name__ == "__main__":
    txns = load_csv(sys.argv[1]) if len(sys.argv) > 1 else SAMPLE
    run_pipeline(txns)
