#!/usr/bin/env python3
"""Phase 2: Signal Analyzer — detect actionable signals from session context.

Reads playbook-logs (last 3 entries) + session summary, uses LLM to identify
signals and recommend actions (spawn subagent, send tip, or skip).

Usage:
    python3 signal_analyzer.py --memory-dir memory/ --session-summary "..." [--idle]
"""

import argparse
import sys

from common import (
    LLMError,
    call_llm,
    extract_json,
    output_json,
    read_effective_playbook,
    read_recent_logs,
)

SYSTEM_PROMPT = """\
You are a signal detection agent for a personal AI assistant system (sinain).
Your job: scan the user's recent session activity and detect actionable signals.

Signal types and recommended actions:
| Signal | Action |
|--------|--------|
| Error or issue repeated in context | sessions_spawn: "Find root cause for: [error]" |
| New tech/topic being explored | sessions_spawn: "Research [topic]: key findings, best practices, pitfalls" |
| Clear next action to suggest | telegram_tip: concise suggestion |
| User stuck (same search/error loop) | sessions_spawn: "Debug [issue]: investigate and propose fix" |
| No meaningful signal | skip |

Signal priority levels:
- HIGH: Repeated errors, build failures, stuck loops — always act
- MEDIUM: New topic exploration, workflow opportunity — act if confident
- LOW: General browsing, social media — skip unless highly relevant

Rules:
- Max 1 recommended action per analysis
- NEVER repeat an action that appears in recent log entries
- Prefer depth (spawn research) over breadth (generic tips)
- If idle (>30 min no activity), set idle=true and skip Phase 2 action
- Confidence: 0.0-1.0 (only recommend actions with confidence > 0.5)

Include a "priority" field ("high"/"medium"/"low") in each signal.

Respond with ONLY a JSON object (no markdown, no explanation):
{
  "signals": [{"description": "signal text", "priority": "high|medium|low"}, ...],
  "recommendedAction": {"action": "sessions_spawn|telegram_tip|skip", "task": "description if not skip", "confidence": 0.7} or null,
  "idle": false
}"""


def build_user_prompt(
    session_summary: str,
    recent_logs: list[dict],
    playbook: str,
    idle: bool,
    current_time: str | None = None,
) -> str:
    parts = []

    if current_time:
        parts.append(f"## Current Time\n{current_time}")

    parts.append(f"## Session Summary\n{session_summary}")

    if idle:
        parts.append("\n## Status: IDLE (>30 min no activity)\nSkip Phase 2 action. Only report if any background signals exist.")

    if recent_logs:
        log_summary = []
        for entry in recent_logs[:6]:
            actions = entry.get("actionsConsidered", [])
            chosen = [a for a in actions if a.get("chosen")]
            skipped = entry.get("skipped", False)
            log_summary.append(
                f"- ts={entry.get('ts', '?')}, idle={entry.get('idle', '?')}, "
                f"actions_chosen={len(chosen)}, skipped={skipped}"
            )
            for a in chosen:
                log_summary.append(f"  -> {a.get('action', '?')}: {a.get('reason', '?')}")
        parts.append(f"\n## Recent Log Entries (last 6)\n" + "\n".join(log_summary))

    if playbook:
        # Truncate playbook to first 50 lines for context
        lines = playbook.splitlines()[:50]
        parts.append(f"\n## Current Playbook (first 50 lines)\n" + "\n".join(lines))

    return "\n".join(parts)


def main():
    parser = argparse.ArgumentParser(description="Phase 2: Signal detection")
    parser.add_argument("--memory-dir", required=True, help="Path to memory/ directory")
    parser.add_argument("--session-summary", required=True, help="Brief session summary from main agent")
    parser.add_argument("--idle", action="store_true", help="User is idle (>30 min)")
    parser.add_argument("--current-time", default=None, help="Current local time string (e.g. 'Monday, 2 March 2026, 14:30 (Europe/Berlin)')")
    args = parser.parse_args()

    playbook = read_effective_playbook(args.memory_dir)
    recent_logs = read_recent_logs(args.memory_dir, days=3)

    user_prompt = build_user_prompt(
        session_summary=args.session_summary,
        recent_logs=recent_logs,
        playbook=playbook,
        idle=args.idle,
        current_time=args.current_time,
    )

    try:
        raw = call_llm(SYSTEM_PROMPT, user_prompt, script="signal_analyzer", json_mode=True)
        result = extract_json(raw)
    except (ValueError, LLMError) as e:
        print(f"[warn] {e}", file=sys.stderr)
        result = {
            "signals": [],
            "recommendedAction": None,
            "idle": args.idle,
        }

    # Suppress low-confidence actions
    action = result.get("recommendedAction")
    if action and isinstance(action, dict):
        confidence = action.get("confidence", 0)
        if confidence < 0.5:
            result["recommendedAction"] = {"action": "skip", "task": None, "confidence": confidence}
            print(f"[info] Suppressed low-confidence action ({confidence})", file=sys.stderr)

    # Ensure idle flag matches CLI arg
    result["idle"] = args.idle
    output_json(result)


if __name__ == "__main__":
    main()
