# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""CLI entry point — handle --query, --file, --explain, --skills, --tools, and hook stdin."""

import json
import os
import select
import sys

from .briefing_signals import _format_explain
from .hook_input import _query_from_filepath, _query_from_hook, _tier_from_hook
from .runner import run_query

try:
    from pulse.brain.brain_query.query_search import _search_skills, _search_tools
except Exception:
    _search_skills = lambda q: ""
    _search_tools = lambda q: ""

try:
    from pulse.brain.brain_search import brain_search
except Exception:
    brain_search = None


def _has_stdin_data() -> bool:
    """Check if there's data on stdin without blocking."""
    if os.name == 'nt':
        return not sys.stdin.isatty()
    return bool(select.select([sys.stdin], [], [], 0.0)[0])


def _cli_arg(flag: str) -> str:
    """Get CLI argument value after flag."""
    if flag not in sys.argv: return ""
    idx = sys.argv.index(flag)
    return sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""


def main():
    for flag, fn in [("--skills", lambda: print(_search_skills(_cli_arg("--skills")))),
                     ("--tools", lambda: print(_search_tools(_cli_arg("--tools"))))]:
        if flag in sys.argv: fn(); return
    if "--explain" in sys.argv:
        q = _cli_arg("--explain")
        if brain_search and q:
            results = brain_search(q, max_per_source=5)
            print(_format_explain(q, results))
        return
    if "--query" in sys.argv:
        b = run_query(_cli_arg("--query"), brief="--brief" in sys.argv)
        if b: print(b)
        return
    if "--file" in sys.argv:
        b = run_query(_query_from_filepath(_cli_arg("--file")), brief="--brief" in sys.argv)
        if b: print(b)
        return
    if _has_stdin_data():
        try:
            raw = sys.stdin.read()
            if not raw.strip(): return
            hook_input = json.loads(raw)
        except (json.JSONDecodeError, Exception):
            return
        query = _query_from_hook(hook_input)
        model_tier = _tier_from_hook(hook_input)
        event = hook_input.get("hook_event_name", "")
        raw_prompt = hook_input.get("prompt", "") if event == "UserPromptSubmit" else ""
        # Wire 1C: lightweight checkpoint on every user prompt
        if event == "UserPromptSubmit" and query:
            try:
                from pulse.brain.session.session_checkpoint import save_checkpoint
                save_checkpoint(
                    agent="claude",
                    task=query[:100],
                    progress="in_progress",
                    findings=[],
                    files_touched=[],
                )
            except Exception:
                pass
            # P47: Ensure a session exists for Claude Code (auto-start on first prompt)
            try:
                from pulse.brain.session.session_lifecycle import get_active_session, start_session
                if not get_active_session("claude"):
                    start_session("claude", task=query[:100])
            except Exception:
                pass
        briefing = run_query(query, raw_prompt=raw_prompt, brief="--brief" in sys.argv, model_tier=model_tier)
        if not briefing: return
        briefing = briefing.encode("utf-8", errors="replace").decode("utf-8", errors="replace")
        print(json.dumps({"hookSpecificOutput": {
            "hookEventName": event or "PreToolUse", "additionalContext": briefing}}))
        return
    print('PULSE Brain Query\nCLI: --query "q" | --file "path" | --skills "q" | --tools "q"\nHook: JSON on stdin')
