"""mood CLI — single entrypoint for ingestion and reads.

Commands:
  init-db                          create the SQLite schema
  sync [--once]                    pull from moodtracker's SQLite; loop unless --once
  query summary                    counts, coverage, freshness, last run
  query entries [--days N]         recent raw entries
  query daily [--days N]           average mood + entry count per day
  query tags [--days N]            average mood per tag (simple correlation)
  query correlate <csv> [--days N] Pearson r between daily mood and an external
                                    day,value CSV (generic cross-source hook —
                                    see store.correlate_with_series docstring)

The `query` commands are the read tool for Adolf: JSON on stdout, no creds needed.
"""
import argparse
import csv
import json
import sys

from . import config, store
from .sync import run_sync, sync_loop


def _conn():
    return store.connect(config.DB_PATH)


def cmd_init_db(_):
    conn = _conn()
    store.init_db(conn)
    print(f"Initialized schema at {config.DB_PATH}")


def cmd_sync(args):
    conn = _conn()
    store.init_db(conn)
    exit_code = 0
    for totals in sync_loop(conn, once=args.once):
        print(json.dumps({"synced": totals}))
        if totals["errors"]:
            print("WARN: " + " | ".join(totals["errors"]), file=sys.stderr)
            exit_code = 1
    return exit_code


def cmd_query(args):
    conn = _conn()
    store.init_db(conn)
    if args.what == "summary":
        out = store.summary(conn)
    elif args.what == "entries":
        out = store.recent_entries(conn, days=args.days)
    elif args.what == "daily":
        out = store.daily_mood(conn, days=args.days)
    elif args.what == "tags":
        out = store.tag_breakdown(conn, days=args.days)
    elif args.what == "correlate":
        external = {}
        with open(args.csv_path, newline="") as f:
            for row in csv.reader(f):
                if len(row) < 2 or row[0].lower() == "day":
                    continue
                try:
                    external[row[0].strip()] = float(row[1])
                except ValueError:
                    continue
        out = store.correlate_with_series(conn, external, days=args.days)
    else:
        print(f"unknown query: {args.what}", file=sys.stderr)
        return 2
    print(json.dumps(out, indent=2, ensure_ascii=False))
    return 0


def build_parser():
    p = argparse.ArgumentParser(prog="mood")
    sub = p.add_subparsers(dest="cmd", required=True)

    sub.add_parser("init-db").set_defaults(func=cmd_init_db)

    ps = sub.add_parser("sync")
    ps.add_argument("--once", action="store_true", help="run one pass and exit")
    ps.set_defaults(func=cmd_sync)

    pq = sub.add_parser("query")
    pqs = pq.add_subparsers(dest="what", required=True)
    pqs.add_parser("summary")
    pe = pqs.add_parser("entries")
    pe.add_argument("--days", type=int, default=30)
    pd = pqs.add_parser("daily")
    pd.add_argument("--days", type=int, default=30)
    pt = pqs.add_parser("tags")
    pt.add_argument("--days", type=int, default=90)
    pc = pqs.add_parser("correlate")
    pc.add_argument("csv_path", help="CSV with 'day,value' rows (day=YYYY-MM-DD)")
    pc.add_argument("--days", type=int, default=90)
    pq.set_defaults(func=cmd_query)

    return p


def main(argv=None):
    args = build_parser().parse_args(argv)
    return args.func(args) or 0


if __name__ == "__main__":
    raise SystemExit(main())
