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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
"""
ReportAgent β€” Full ReACT Analytical Agent
Replaces the 72-line stub with a complete ReACT (Reasoning + Acting) loop
powered by three specialized tools (InsightForge, PanoramaSearch, QuickSearch).

Architecture:
- InsightForgeTool:   Hybrid broad-spectrum retriever (vector + graph + community)
- PanoramaSearchTool: Entity-type sweep for macro-level statistics
- QuickSearchTool:    Fast single-entity lookup with direct relationships
"""
from __future__ import annotations
import logging
logger = logging.getLogger(__name__)


import asyncio
import json
from datetime import datetime, timezone
from typing import Any, Dict, List, Literal, Optional

from pydantic import BaseModel, Field

from ..core.neo4j_store import Neo4jStore
from ..core.llm_factory import UnifiedLLMProvider
from ..config import settings


# ── Result models ───────────────────────────────────────────────────────────

class ReportSection(BaseModel):
    title: str
    content: str


class ReportResult(BaseModel):
    topic: str
    executive_summary: str
    sections: Dict[str, str] = Field(default_factory=dict)
    key_entities: List[str] = Field(default_factory=list)
    confidence: float = 0.0
    tool_calls_made: int = 0
    generated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
    markdown: str = ""


# ── Specialized analytical tools ─────────────────────────────────────────────

class InsightForgeTool:
    """
    Broad-spectrum hybrid retriever: merges vector similarity + graph
    neighborhood + community summaries for cross-entity insights.
    Use for open-ended analytical questions.
    """
    name = "InsightForge"
    description = (
        "Hybrid broad-spectrum retriever combining vector similarity, graph "
        "neighborhood, and community summaries. Best for open-ended analysis."
    )

    def __init__(self, store: Neo4jStore, llm: UnifiedLLMProvider) -> None:
        self.store = store
        self.llm = llm

    async def run(self, query: str, k: int = 8, tenant_id: Optional[str] = None) -> List[Dict[str, Any]]:
        results: List[Dict[str, Any]] = []

        # 1. Hybrid vector + BM25 chunk retrieval
        try:
            embedding = await self.llm.embed(query)
            bm25_task = self.store.bm25_search(query, k=k, tenant_id=tenant_id)
            vector_task = self.store.search(query_vector=embedding, k=k, tenant_id=tenant_id)
            bm25_r, vector_r = await asyncio.gather(
                bm25_task, vector_task, return_exceptions=True
            )
            for r in (bm25_r if not isinstance(bm25_r, Exception) else []):
                r["source"] = "bm25"
                results.append(r)
            for r in (vector_r if not isinstance(vector_r, Exception) else []):
                r["source"] = "vector"
                results.append(r)
        except Exception:
            pass

        # 2. Graph neighborhood of top chunk entities
        try:
            entity_query = """
            CALL db.index.fulltext.queryNodes('chunk_text_index', $q)
            YIELD node, score
            WHERE ($tenant_id IS NULL OR node.tenant_id = $tenant_id)
            MATCH (node)-[:MENTIONS]->(e:Entity)
            WHERE ($tenant_id IS NULL OR e.tenant_id = $tenant_id)
            RETURN DISTINCT e.name as name, e.summary as summary
            LIMIT 10
            """
            entity_rows = await self.store.execute_query(
                entity_query, {"q": query, "tenant_id": tenant_id}
            )
            for row in entity_rows:
                if row.get("summary"):
                    results.append({
                        "text": f"[Entity Profile] {row['name']}: {row['summary']}",
                        "source": "entity_summary",
                        "retrieval_method": "insight_forge",
                    })
        except Exception:
            pass

        # 3. Community summaries
        try:
            community_query = """
            MATCH (e:Entity)
            WHERE e.community_id IS NOT NULL
              AND ($tenant_id IS NULL OR e.tenant_id = $tenant_id)
            WITH e.community_id as cid, collect(e.name)[..5] as members
            RETURN cid, members
            ORDER BY size(members) DESC
            LIMIT 3
            """
            communities = await self.store.execute_query(community_query, {"tenant_id": tenant_id})
            for comm in communities:
                member_summary = ", ".join(comm.get("members", []))
                results.append({
                    "text": (
                        f"[Community {comm['cid']} β€” "
                        f"{len(comm.get('members', []))} entities]: "
                        f"{member_summary}"
                    ),
                    "source": "community",
                    "retrieval_method": "insight_forge",
                })
        except Exception:
            pass

        # Deduplicate by text
        seen: set = set()
        unique: List[Dict] = []
        for r in results:
            key = r.get("text", "")[:80]
            if key and key not in seen:
                seen.add(key)
                unique.append(r)

        return unique[:k]


class PanoramaSearchTool:
    """
    Macro-level entity sweep: returns all entities of a given type with
    statistics. Useful for 'How many X?', 'List all Y', 'What types of Z?'
    """
    name = "PanoramaSearch"
    description = (
        "Broad entity sweep returning all nodes of a specified type. "
        "Best for: counting, listing, macro-level statistics."
    )

    def __init__(self, store: Neo4jStore) -> None:
        self.store = store

    async def run(
        self, entity_type: str = "Entity", limit: int = 30, tenant_id: Optional[str] = None
    ) -> List[Dict[str, Any]]:
        """Return entities of the given type with their summaries."""
        query = """
        MATCH (e:Entity)
        WHERE (e.type = $type OR $type = 'Entity')
          AND ($tenant_id IS NULL OR e.tenant_id = $tenant_id)
        RETURN e.name as name, e.type as type,
               e.summary as summary,
               size((e)--()) as degree
        ORDER BY degree DESC
        LIMIT $limit
        """
        try:
            rows = await self.store.execute_query(
                query, {"type": entity_type, "limit": limit, "tenant_id": tenant_id}
            )
            results = []
            for r in rows:
                text = f"[{r.get('type', 'Entity')}] {r.get('name', '')}"
                if r.get("summary"):
                    text += f": {r['summary']}"
                results.append({
                    "text": text,
                    "name": r.get("name"),
                    "type": r.get("type"),
                    "degree": r.get("degree", 0),
                    "retrieval_method": "panorama_search",
                })
            return results
        except Exception as exc:
            logger.info(f"[PanoramaSearch] Error: {exc}")
            return []


class QuickSearchTool:
    """
    Fast single-entity lookup by name with direct 1-hop relationships.
    Useful for 'Who is X?', 'What does Y do?', 'Tell me about Z'.
    """
    name = "QuickSearch"
    description = (
        "Fast entity lookup by name. Returns entity summary + direct "
        "relationships. Best for specific entity questions."
    )

    def __init__(self, store: Neo4jStore, llm: UnifiedLLMProvider) -> None:
        self.store = store
        self.llm = llm

    async def run(self, entity_name: str, tenant_id: Optional[str] = None) -> List[Dict[str, Any]]:
        """Look up an entity and return its profile + connections."""
        # Exact match first, then fuzzy BM25
        entity_query = """
        MATCH (e:Entity)
        WHERE (e.name = $name OR toLower(e.name) CONTAINS toLower($name))
          AND ($tenant_id IS NULL OR e.tenant_id = $tenant_id)
        RETURN e.name as name, e.type as type, e.summary as summary
        LIMIT 3
        """
        try:
            entities = await self.store.execute_query(
                entity_query, {"name": entity_name, "tenant_id": tenant_id}
            )
        except Exception:
            entities = []

        results: List[Dict[str, Any]] = []
        for entity in entities:
            name = entity.get("name", entity_name)
            summary = entity.get("summary", "")
            entry: Dict[str, Any] = {
                "name": name,
                "type": entity.get("type", "Entity"),
                "retrieval_method": "quick_search",
            }

            # Get direct relationships
            rel_query = """
            MATCH (e:Entity {name: $name})-[r]-(other:Entity)
            WHERE ($tenant_id IS NULL OR (e.tenant_id = $tenant_id AND other.tenant_id = $tenant_id AND r.tenant_id = $tenant_id))
            RETURN type(r) as rel_type,
                   other.name as other_name,
                   other.type as other_type
            LIMIT 20
            """
            try:
                rels = await self.store.execute_query(
                    rel_query, {"name": name, "tenant_id": tenant_id}
                )
                rel_lines = [
                    f"{r['rel_type']} β†’ {r['other_name']} ({r['other_type']})"
                    for r in rels
                ]
                rel_text = "; ".join(rel_lines) if rel_lines else "no connections"
            except Exception:
                rel_text = "unavailable"

            text_parts = [f"[Entity] {name}"]
            if summary:
                text_parts.append(summary)
            text_parts.append(f"Connections: {rel_text}")
            entry["text"] = " | ".join(text_parts)
            results.append(entry)

        return results


# ── Main ReportAgent ──────────────────────────────────────────────────────────

class ReportAgent:
    """
    Full ReACT analytical reporting agent.

    Workflow:
      DECOMPOSE  β†’ Break topic into 3-5 sub-questions
      REACT LOOP β†’ For each sub-question:
                     THINK β†’ pick best tool
                     ACT   β†’ run InsightForge / PanoramaSearch / QuickSearch
                     OBS   β†’ record retrieved context
                     WRITE β†’ draft answer section
      COMPILE    β†’ Assemble all sections into a structured markdown report
    """

    MAX_REACT_LOOPS = 6
    TOOLS_DESC = """
Available tools:
- InsightForge(query):           Hybrid broad-spectrum retriever. Best for analytical questions.
- PanoramaSearch(entity_type):   Sweep all entities of a type.  Best for counting/listing.
- QuickSearch(entity_name):      Fast entity lookup + connections. Best for "Who is X?" questions.
"""

    def __init__(self, store: Neo4jStore, llm: UnifiedLLMProvider) -> None:
        self.store = store
        self.llm = llm
        self.insight_forge = InsightForgeTool(store, llm)
        self.panorama = PanoramaSearchTool(store)
        self.quick_search = QuickSearchTool(store, llm)
        self._tool_calls = 0

    # ── Public ─────────────────────────────────────────────────────────────

    async def generate_report(
        self,
        topic: str,
        report_type: Literal["executive", "detailed", "entity_focus"] = "detailed",
        target_entity: Optional[str] = None,
        tenant_id: Optional[str] = None,
    ) -> ReportResult:
        """
        Generate an analytical report on the given topic.

        Args:
            topic:         High-level topic or question
            report_type:   "executive" (short), "detailed" (full), "entity_focus" (scoped)
            target_entity: For entity_focus β€” name of the entity to focus on

        Returns:
            ReportResult with sections, summary, and compiled markdown
        """
        self._tool_calls = 0

        # 1. Decompose topic into sub-questions
        sub_questions = await self._decompose_topic(
            topic, report_type, target_entity
        )

        # 2. ReACT loop for each sub-question
        sections: Dict[str, str] = {}
        all_contexts: List[str] = []
        key_entities: List[str] = []

        total_confidence_score = 0.0

        for question in sub_questions:
            section_content, contexts, entities, confidence = await self._react_loop(question, tenant_id=tenant_id)
            if section_content:
                sections[question] = section_content
            all_contexts.extend(contexts)
            key_entities.extend(entities)
            total_confidence_score += confidence

        # 3. Executive summary
        exec_summary = await self._write_executive_summary(topic, sections)

        # 4. Key entities dedup
        key_entities = list(dict.fromkeys(key_entities))[:10]

        # 5. Confidence logic updated to use actual contextual relevancy confidence rather than length
        overall_confidence = round(total_confidence_score / max(len(sub_questions), 1), 2)

        # 6. Compile markdown
        markdown = self._compile_markdown(
            topic, exec_summary, sections, key_entities
        )

        return ReportResult(
            topic=topic,
            executive_summary=exec_summary,
            sections=sections,
            key_entities=key_entities,
            confidence=overall_confidence,
            tool_calls_made=self._tool_calls,
            markdown=markdown,
        )

    # ── Internal steps ─────────────────────────────────────────────────────

    async def _decompose_topic(
        self,
        topic: str,
        report_type: str,
        target_entity: Optional[str],
    ) -> List[str]:
        """Ask LLM to decompose the topic into sub-questions."""
        n = 3 if report_type == "executive" else 5
        focus = (
            f"Focus specifically on the entity '{target_entity}'."
            if target_entity
            else ""
        )
        prompt = f"""You are planning an analytical report about: "{topic}"
{focus}

Generate {n} specific sub-questions that would together create a complete report.
Each sub-question should be answerable from a knowledge graph.

Return ONLY a JSON list of strings:
["question 1", "question 2", ...]"""

        try:
            response = await self.llm.complete(prompt, temperature=0.3)
            cleaned = response.strip()
            for marker in ("```json", "```"):
                if marker in cleaned:
                    cleaned = cleaned.split(marker)[1].split("```")[0]
            questions = json.loads(cleaned.strip())
            if isinstance(questions, list) and questions:
                return [str(q) for q in questions[:n]]
        except Exception:
            pass
        # Fallback
        return [
            f"What are the main entities related to {topic}?",
            f"What are the key relationships in {topic}?",
            f"What are the most important findings about {topic}?",
        ]

    async def _react_loop(
        self, question: str, tenant_id: Optional[str] = None
    ) -> tuple[str, List[str], List[str], float]:
        """
        Run a ReACT iteration for one sub-question.
        Returns (section_content, context_texts, entity_names, confidence_score).
        """
        collected_contexts: List[str] = []
        entity_names: List[str] = []
        observations: List[str] = []

        for step in range(self.MAX_REACT_LOOPS):
            # THINK: which tool next?
            thought, tool_name, tool_arg = await self._think(
                question, observations
            )

            observations.append(f"[Thought]\n{thought}")

            if tool_name == "DONE":
                break

            # ACT: run the chosen tool
            tool_results = await self._act(tool_name, tool_arg, tenant_id=tenant_id)
            self._tool_calls += 1

            if tool_results:
                obs_texts = [r.get("text", str(r))[:300] for r in tool_results]
                obs_summary = "\n".join(f"β€’ {t}" for t in obs_texts[:5])
                observations.append(f"[{tool_name}({tool_arg})]\n{obs_summary}")
                collected_contexts.extend(obs_texts)

                # Collect entity names
                for r in tool_results:
                    if r.get("name"):
                        entity_names.append(r["name"])
            else:
                observations.append(f"[{tool_name}({tool_arg})] No results.")
                break

        # WRITE: draft the section answer
        if collected_contexts:
            section, confidence = await self._write_section_with_confidence(question, collected_contexts)
        else:
            section = "Insufficient data found in the knowledge graph."
            confidence = 0.0

        return section, collected_contexts, entity_names, confidence

    async def _think(
        self, question: str, observations: List[str]
    ) -> tuple[str, str, str]:
        """Decide which tool to call next, or return DONE."""
        obs_text = "\n".join(observations[-3:]) if observations else "None yet."

        prompt = f"""You are deciding the next action to answer:
"{question}"

{self.TOOLS_DESC}
Observations so far:
{obs_text}

If you have enough information to write a good answer, choose the DONE tool.
Otherwise, deeply analyze the observations in a step-by-step thought and pick the most appropriate tool."""

        class AgentAction(BaseModel):
            thought: str = Field(description="Step by step reasoning analyzing the observations and deciding what to do next.")
            tool_name: Literal["InsightForge", "PanoramaSearch", "QuickSearch", "DONE"] = Field(description="The chosen tool.")
            tool_arg: str = Field(description="The argument to pass to the tool. Empty if DONE.")

        try:
            action: AgentAction = await self.llm.complete_structured(
                prompt=prompt,
                response_model=AgentAction,
                system_prompt="You are a meticulous investigative agent generating JSON."
            )
            return action.thought, action.tool_name, action.tool_arg
        except Exception as exc:
            return f"Failed to parse or error: {exc}", "DONE", ""

    async def _act(
        self, tool_name: str, tool_arg: str, tenant_id: Optional[str] = None
    ) -> List[Dict[str, Any]]:
        """Dispatch tool call and return results."""
        try:
            if tool_name == "InsightForge":
                return await self.insight_forge.run(tool_arg, tenant_id=tenant_id)
            elif tool_name == "PanoramaSearch":
                return await self.panorama.run(tool_arg, tenant_id=tenant_id)
            elif tool_name == "QuickSearch":
                return await self.quick_search.run(tool_arg, tenant_id=tenant_id)
        except Exception as exc:
            logger.info(f"[ReportAgent] Tool {tool_name} failed: {exc}")
        return []

    async def _write_section_with_confidence(
        self, question: str, contexts: List[str]
    ) -> tuple[str, float]:
        """Generate a report section from retrieved contexts and provide a structured confidence score."""
        context_text = "\n\n".join(f"[Source {i+1}]: {c}" for i, c in enumerate(contexts[:8]))

        prompt = f"""Write a factual, well-structured paragraph answering:
"{question}"

Based ONLY on the following knowledge graph data:
{context_text}

Instructions:
- Be specific and cite entities by name
- Do not hallucinate or add information not in the sources
- 2-4 sentences is ideal
- Also output a confidence score from 0.0 to 1.0 reflecting how fully the data answers the question.
"""
        class SectionResult(BaseModel):
            content: str = Field(description="The 2-4 sentence report section or state data is insufficient.")
            confidence: float = Field(description="Confidence score 0.0 to 1.0 based on data sufficiency")

        try:
            res: SectionResult = await self.llm.complete_structured(
                prompt=prompt,
                response_model=SectionResult,
                system_prompt="You are an analytical writer crafting a knowledge-graph report section.",
            )
            return res.content, res.confidence
        except Exception:
            return "Unable to generate section due to LLM error.", 0.0

    async def _write_executive_summary(
        self, topic: str, sections: Dict[str, str]
    ) -> str:
        """Synthesize all sections into a 3-sentence executive summary."""
        section_text = "\n\n".join(
            f"## {q}\n{a}" for q, a in list(sections.items())[:5]
        )
        prompt = f"""Write a 2-3 sentence executive summary for a report on: "{topic}"

Report findings:
{section_text[:2000]}

Executive summary (concise, factual, highlight the most important finding):"""
        try:
            return await self.llm.complete(prompt, temperature=0.3)
        except Exception:
            return f"Analysis of {topic} based on knowledge graph data."

    def _compile_markdown(
        self,
        topic: str,
        exec_summary: str,
        sections: Dict[str, str],
        key_entities: List[str],
    ) -> str:
        lines = [
            f"# Report: {topic}",
            f"*Generated: {datetime.now(timezone.utc).replace(tzinfo=None).strftime('%Y-%m-%d %H:%M UTC')}*\n",
            "## Executive Summary",
            exec_summary,
            "",
        ]
        for question, content in sections.items():
            lines.append(f"## {question}")
            lines.append(content)
            lines.append("")

        if key_entities:
            lines.append("## Key Entities Referenced")
            lines.append(", ".join(key_entities))

        return "\n".join(lines)