#!/usr/bin/env python3
"""Log work expenses to MongoDB (wip.work_expenses).

Usage:
    python log_expense.py <type> <account> <date> <note> <s2_url_1> [s2_url_2]

    type:    "meal" or "mileage"
    account: e.g. "LTISD"
    date:    YYYY-MM-DD
    note:    free-text context (quote if it has spaces)
    s2_url:  one or more S2 URLs of uploaded files

Rules enforced:
    - meal:    exactly 1 file per invocation
    - mileage: exactly 2 files per invocation (start + end odometer)
"""

import sys
from pymongo import MongoClient

def main():
    args = sys.argv[1:]
    if len(args) < 5:
        print("Usage: log_expense.py <type> <account> <date> <note> <s2_url_1> [s2_url_2]")
        sys.exit(1)

    exp_type = args[0]
    account = args[1]
    date = args[2]
    note = args[3]
    files = args[4:]

    if exp_type not in ("meal", "mileage"):
        print(f"Error: type must be 'meal' or 'mileage', got '{exp_type}'")
        sys.exit(1)

    if exp_type == "meal" and len(files) != 1:
        print(f"Error: meal entries must have exactly 1 file, got {len(files)}")
        sys.exit(1)

    if exp_type == "mileage" and len(files) != 2:
        print(f"Error: mileage entries must have exactly 2 files (start + end odometer), got {len(files)}")
        sys.exit(1)

    client = MongoClient("mongodb://root:3wwfoUjyk2E2zWELXFlLuHqfw1ALlOp4pb2H5Vq3TImbMIHL2h1u8Jej2mjzCPl@docdb.connorrhodes.com:35563")
    db = client["wip"]
    col = db["work_expenses"]

    doc = {
        "files": files,
        "date": date,
        "type": exp_type,
        "account": account,
        "note": note,
        "status": "todo"
    }

    result = col.insert_one(doc)
    print(f"Inserted {exp_type} for {account} on {date}: {result.inserted_id}")

if __name__ == "__main__":
    main()
