#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary.
"""CLI entry-point and run() for the Log Distiller daemon."""
import logging
import time

from pulse.daemons.distiller.distiller import (
    _build_extractors,
    _load_state,
    _save_state,
    _discover_logs,
    _process_log,
    POLL_INTERVAL,
)

log = logging.getLogger("pulse.distiller")


def run(args) -> None:
    """Main entry-point."""
    level = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(level=level, format="%(levelname)s %(name)s: %(message)s")
    extractors = _build_extractors()
    try:
        from pulse.daemons.distiller.extractors.session_extractor import SessionExtractor
        session_extractor = SessionExtractor()
    except Exception as exc:
        log.warning("SessionExtractor unavailable: %s", exc)
        session_extractor = None

    class _NoopSession:
        def summarize(self, *a, **kw):
            return False

    if session_extractor is None:
        session_extractor = _NoopSession()

    def _run_once():
        state = {} if args.reprocess else _load_state()
        total = 0
        for lp in _discover_logs(getattr(args, "log", None)):
            n = _process_log(
                lp, state, extractors, session_extractor,
                dry_run=args.dry_run,
                verbose=args.verbose,
                reprocess=args.reprocess,
            )
            total += n
            if n > 0:
                log.info("Processed %d pairs from %s", n, lp.name)
        if not args.dry_run:
            _save_state(state)
        if args.verbose:
            counts = {e.name: e.extracted_count for e in extractors}
            log.info("Extractor totals: %s", counts)
        return total

    if args.once or args.dry_run or args.reprocess:
        total = _run_once()
        log.info("Done. Total pairs processed: %d", total)
        return

    log.info("Distiller daemon started (poll every %ds)", POLL_INTERVAL)
    while True:
        try:
            _run_once()
        except Exception as exc:
            log.error("Run failed: %s", exc)
        time.sleep(POLL_INTERVAL)




def main():
    import argparse
    parser = argparse.ArgumentParser(description="PULSE Log Distiller")
    parser.add_argument("--once", action="store_true",
                        help="Run once and exit (default: daemon mode)")
    parser.add_argument("--verbose", action="store_true",
                        help="Enable debug logging")
    parser.add_argument("--dry-run", action="store_true",
                        help="Parse and report without writing to brain")
    parser.add_argument("--reprocess", action="store_true",
                        help="Ignore watermarks and reprocess all log content")
    parser.add_argument("--log", metavar="PATH",
                        help="Process a specific log file only")
    parsed_args = parser.parse_args()
    run(parsed_args)


if __name__ == "__main__":
    main()
