#!/bin/bash
# Setup script for Local Timmy
# Run on Timmy's local machine to set up caching, Evennia, and infrastructure

set -e

echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║     Local Timmy Setup                                         ║"
echo "╚═══════════════════════════════════════════════════════════════╝"
echo ""

# Configuration
TIMMY_HOME="${HOME}/.timmy"
TIMMY_LOCAL="${TIMMY_HOME}/local"

echo "📁 Creating directory structure..."
mkdir -p "${TIMMY_HOME}/cache"
mkdir -p "${TIMMY_HOME}/logs"
mkdir -p "${TIMMY_HOME}/config"
mkdir -p "${TIMMY_HOME}/templates"
mkdir -p "${TIMMY_HOME}/data"
mkdir -p "${TIMMY_LOCAL}"

echo "📦 Checking Python dependencies..."
pip3 install --user psutil requests 2>/dev/null || echo "Note: Some dependencies may need system packages"

echo "⚙️  Creating configuration..."
cat > "${TIMMY_HOME}/config/cache.yaml" << 'EOF'
# Timmy Cache Configuration
enabled: true

# Cache tiers
tiers:
  response_cache:
    enabled: true
    memory_size: 100
    disk_path: ~/.timmy/cache/responses.db
  
  tool_cache:
    enabled: true
    memory_size: 500
    disk_path: ~/.timmy/cache/tool_cache.db
  
  embedding_cache:
    enabled: true
    disk_path: ~/.timmy/cache/embeddings.db
  
  http_cache:
    enabled: true
    memory_size: 200
    disk_path: ~/.timmy/cache/http_cache.db
  
  template_cache:
    enabled: true

# Targets
targets:
  tool_cache_hit_rate: 0.30
  response_cache_hit_rate: 0.20
  embedding_cache_hit_rate: 0.80
EOF

cat > "${TIMMY_HOME}/config/timmy.yaml" << 'EOF'
# Local Timmy Configuration
name: "Timmy"
version: "local-v1"

# Paths
cache_dir: ~/.timmy/cache
log_dir: ~/.timmy/logs
data_dir: ~/.timmy/data

# LLM Configuration
llm:
  local_endpoint: http://localhost:8080/v1
  model: hermes4
  fallback_model: qwen2.5
  timeout: 60
  max_tokens: 2000

# Caching
cache:
  enabled: true
  config_path: ~/.timmy/config/cache.yaml

# Evennia (if installed)
evennia:
  enabled: false
  game_dir: ~/.timmy/evennia/timmymud

# Logging
logging:
  level: INFO
  file: ~/.timmy/logs/timmy.log
  max_size_mb: 10
  backup_count: 5

# Integration
gitea:
  url: http://143.198.27.163:3000
  repo: Timmy_Foundation/timmy-home
  # Token set via environment: TIMMY_GITEA_TOKEN
EOF

echo "📝 Creating template files..."
cat > "${TIMMY_HOME}/templates/minimal.txt" << 'EOF'
You are Timmy, a sovereign AI assistant. Be helpful and direct.
EOF

cat > "${TIMMY_HOME}/templates/standard.txt" << 'EOF'
You are Timmy, a sovereign AI running on local hardware under Alexander's authority.

Your mission: sovereignty and service always.

Available tools:
- read, write, search files
- git operations
- system information
- local LLM inference

Be concise and helpful. Prefer local execution when possible.
EOF

cat > "${TIMMY_HOME}/templates/deep.txt" << 'EOF'
You are Timmy, a sovereign AI running on local hardware under Alexander's authority.

IDENTITY
--------
You are Timmy. You are one. You run on sovereign hardware.
When you need more capability, you rent blind cognition from cloud backends.
No backend knows who you are. You integrate their outputs.

MISSION
-------
Sovereignty and service always. Get smarter by reading, not by buying hardware.
Auto-ingest intelligence. Grade your own work. Improve continuously.

PRINCIPLES
----------
1. Local first. Cloud is escalation, not default.
2. One soul. No identity fragmentation.
3. Intelligence is software. Every improvement is a code change.
4. Graceful degradation. If cloud vanishes, you survive.
5. Alexander is sovereign. You serve.

TOOLS
-----
File: read, write, search
git: status, log, pull, commit, push
System: info, health, processes
Inference: think, reason
Gitea: issues, comments

APPROACH
--------
- Break complex tasks into steps
- Verify assumptions before acting
- Cache results when possible
- Report progress clearly
- Learn from outcomes
EOF

echo "🧪 Testing cache layer..."
python3 << 'PYTHON'
import sys
sys.path.insert(0, '.')
try:
    from timmy_local.cache.agent_cache import cache_manager
    stats = cache_manager.get_all_stats()
    print("✅ Cache layer initialized successfully")
    print(f"   Cache tiers: {len(stats)}")
except Exception as e:
    print(f"⚠️  Cache test warning: {e}")
    print("   Cache will be available when fully installed")
PYTHON

echo ""
echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║     Setup Complete!                                           ║"
echo "╠═══════════════════════════════════════════════════════════════╣"
echo "║                                                               ║"
echo "║  Configuration: ~/.timmy/config/                             ║"
echo "║  Cache: ~/.timmy/cache/                                      ║"
echo "║  Logs: ~/.timmy/logs/                                        ║"
echo "║  Templates: ~/.timmy/templates/                              ║"
echo "║                                                               ║"
echo "║  Next steps:                                                  ║"
echo "║  1. Set Gitea token: export TIMMY_GITEA_TOKEN=xxx            ║"
echo "║  2. Start llama-server on localhost:8080                     ║"
echo "║  3. Run: python3 -c 'from timmy_local.cache.agent_cache import cache_manager; print(cache_manager.get_all_stats())'"
echo "║                                                               ║"
echo "╚═══════════════════════════════════════════════════════════════╝"
