#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Generate Knowledge Anchors: One-time tool to build knowledge_anchors.json (Phase 6).

Creates pre-computed embeddings for 50 anchor phrases per knowledge type.
These anchors are used by semantic_extractor.py to classify sentences
by semantic similarity rather than regex patterns.

Usage:
    pip install sentence-transformers
    python generate_anchors.py

Output: pulse/config/knowledge_anchors.json

Dependencies: sentence-transformers>=2.2.0
"""

import json
import sys
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent

CONFIG_DIR = ROOT_DIR / "Configuration"
ANCHORS_FILE = CONFIG_DIR / "knowledge_anchors.json"

# === ANCHOR PHRASES (50 per type) ===

LEARNING_ANCHORS = [
    "We learned that", "The key insight is", "It turns out",
    "What worked was", "The takeaway is", "Important discovery",
    "Now I understand", "The trick is", "Best practice is",
    "I discovered that", "We found out", "The real issue was",
    "Turns out the problem was", "After investigation we found",
    "The root cause is", "We now know that", "Key finding",
    "Confirmed that", "Verified that", "Evidence shows",
    "The data indicates", "After testing we learned",
    "The experiment showed", "Research revealed",
    "An important observation", "We realized that",
    "It became clear that", "The answer is",
    "What we discovered was", "The breakthrough was",
    "A critical insight", "We identified that",
    "Investigation revealed", "Analysis showed",
    "The underlying cause was", "We determined that",
    "Testing confirmed", "The evidence suggests",
    "A key observation", "We noticed that",
    "The pattern shows", "Data confirms",
    "After review we found", "The conclusion is",
    "We established that", "Findings indicate",
    "The main discovery was", "We uncovered that",
    "Examination revealed", "The core finding is",
]

FAILURE_ANCHORS = [
    "This didn't work because", "The error was caused by",
    "It failed when", "The bug was", "What went wrong",
    "This approach failed", "The crash was caused by",
    "A regression occurred", "The test failed because",
    "We lost data when", "The system broke when",
    "This caused a problem", "The vulnerability was",
    "Performance degraded when", "The timeout happened because",
    "A race condition occurred", "Memory leaked when",
    "The build failed due to", "The deployment broke",
    "An exception was thrown", "The process crashed",
    "Data was corrupted when", "The migration failed",
    "Security was compromised", "The API returned errors",
    "Configuration was wrong", "Dependencies conflicted",
    "The integration broke", "Permission was denied",
    "The connection timed out", "Resources were exhausted",
    "The queue overflowed", "State became inconsistent",
    "The lock was never released", "Concurrency issues arose",
    "The rollback failed", "Validation was bypassed",
    "The cache was stale", "The index was missing",
    "Serialization failed", "The schema was incompatible",
    "Authentication failed", "Rate limiting kicked in",
    "The circuit breaker tripped", "Disk space ran out",
    "The certificate expired", "DNS resolution failed",
    "The webhook was not received", "The batch job hung",
    "The retry logic looped", "The fallback also failed",
]

PATTERN_ANCHORS = [
    "The pattern is", "This always happens when",
    "Every time we", "A recurring issue is",
    "The convention is", "Rule of thumb",
    "Best practice", "The standard approach",
    "We consistently see", "This tends to happen",
    "The typical flow is", "Usually the fix is",
    "In general you should", "The common case is",
    "A proven approach", "What typically works",
    "The established way", "The recommended practice",
    "A reliable method", "The go-to solution",
    "This sequence works", "The proven workflow",
    "A repeatable process", "The standard procedure",
    "The expected behavior", "The normal flow",
    "A common pitfall", "Watch out for",
    "The anti-pattern is", "Avoid doing this",
    "Never use this approach", "Always check first",
    "The safe way is", "The correct order is",
    "Prerequisites include", "Before starting always",
    "After completing always", "The checklist includes",
    "Key steps are", "The critical path is",
    "Dependencies require", "The bottleneck is usually",
    "The tradeoff is", "The constraint is",
    "Performance scales with", "The limit is",
    "The threshold should be", "Quality gates require",
    "The acceptance criteria", "Success means",
]

DECISION_ANCHORS = [
    "We decided to", "The decision was to",
    "We chose to use", "Going with this approach",
    "The architecture will be", "We're switching to",
    "The strategy is to", "We picked this because",
    "After evaluation we selected", "The plan is to",
    "We agreed on", "The final choice was",
    "We opted for", "The preferred solution is",
    "We committed to", "The direction is",
    "The tradeoff we accepted", "We prioritized",
    "The approach we're taking", "The design choice was",
    "We rejected the alternative", "Instead of X we chose Y",
    "The requirement dictates", "Based on constraints",
    "The recommendation is", "We aligned on",
    "The consensus was", "After discussion we chose",
    "The technical decision", "The business decision",
    "We will migrate to", "We will deprecate",
    "The new standard is", "We're adopting",
    "Phase one will focus on", "The priority order is",
    "We deferred this until", "The timeline requires",
    "The minimum viable approach", "We scoped down to",
    "The release criteria", "We set the threshold at",
    "The target metric is", "We will measure by",
    "The acceptance test is", "We defined success as",
    "The rollback plan is", "The migration path is",
    "The compatibility requirement", "We committed to maintaining",
]

SOLUTION_ANCHORS = [
    "The fix was", "We solved it by",
    "The solution is", "The workaround is",
    "What fixed it was", "Resolved by using",
    "The correct approach is", "This resolved the issue",
    "Applied the fix", "The patch addresses",
    "Implemented the solution", "The resolution was",
    "We corrected this by", "The repair involved",
    "Successfully resolved", "The remedy was",
    "We addressed this by", "The mitigation is",
    "Recovered by doing", "Restored functionality with",
    "The hotfix was", "We patched this by",
    "The cleanup involved", "Refactored to fix",
    "Replaced with a working version", "Upgraded to resolve",
    "Downgraded to fix", "Reverted the change",
    "Applied a migration", "Updated the configuration",
    "Fixed the permissions", "Corrected the path",
    "Adjusted the timeout", "Increased the limit",
    "Added the missing check", "Removed the broken code",
    "Simplified the logic", "Rewrote the function",
    "Added error handling", "Implemented retry logic",
    "Added validation", "Fixed the race condition",
    "Added proper locking", "Fixed the memory leak",
    "Optimized the query", "Added an index",
    "Fixed the serialization", "Corrected the encoding",
    "Updated the schema", "Fixed the compatibility issue",
]

ALL_ANCHORS = {
    "learning": LEARNING_ANCHORS,
    "failure": FAILURE_ANCHORS,
    "pattern": PATTERN_ANCHORS,
    "decision": DECISION_ANCHORS,
    "solution": SOLUTION_ANCHORS,
}


def generate_anchors():
    """Generate knowledge_anchors.json with pre-computed embeddings."""
    try:
        from sentence_transformers import SentenceTransformer
    except ImportError:
        print("ERROR: sentence-transformers not installed.")
        print("Install with: pip install sentence-transformers")
        sys.exit(1)

    print("Loading model (all-MiniLM-L6-v2)...")
    model = SentenceTransformer("all-MiniLM-L6-v2")

    anchors_data = {"anchors": {}, "model": "all-MiniLM-L6-v2", "version": 1}

    total = 0
    for knowledge_type, phrases in ALL_ANCHORS.items():
        print(f"  Encoding {len(phrases)} {knowledge_type} anchors...")
        embeddings = model.encode(phrases, show_progress_bar=False)

        anchors_data["anchors"][knowledge_type] = [
            {
                "phrase": phrase,
                "embedding": emb.tolist(),
            }
            for phrase, emb in zip(phrases, embeddings)
        ]
        total += len(phrases)

    # Write to config
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    ANCHORS_FILE.write_text(
        json.dumps(anchors_data, indent=2), encoding="utf-8"
    )

    print(f"\nGenerated {total} anchor embeddings -> {ANCHORS_FILE}")
    print(f"File size: {ANCHORS_FILE.stat().st_size // 1024} KB")


if __name__ == "__main__":
    generate_anchors()
