#!/usr/bin/env python3
"""
The R-Complex — Territory, Threat Detection & Reflexes
Scans the environment for threats and monitors system territory.
Provides threat_level to amygdala and territory_status to thalamus.
"""
import json
import random
from datetime import datetime
from pathlib import Path
from brain.state import BASE_DIR

TERRITORY_FILE = BASE_DIR / "territory.json"

DEFAULT_TERRITORY = {
    "id": "ghojualamanchu_v3",
    "name": "Ghojualamanchu v3 Territory",
    "claimed": True,
    "status": "safe",
    "last_scan": None,
    "conditions": {
        "system_load": 0.0,
        "memory_available_mb": 0,
        "disk_free_gb": 0,
        "uptime_hours": 0
    }
}

def scan_territory():
    """
    Scan system territory: CPU load, memory, disk, uptime.
    Returns territory status dict.
    """
    try:
        # Read /proc for system stats
        loadavg = Path("/proc/loadavg").read_text().split() if Path("/proc/loadavg").exists() else ["0", "0", "0"]
        meminfo = Path("/proc/meminfo").read_text() if Path("/proc/meminfo").exists() else ""
        uptime = Path("/proc/uptime").read_text().split()[0] if Path("/proc/uptime").exists() else "0"

        system_load = float(loadavg[0]) if loadavg else 0.0

        # Parse memory
        mem_total = 0
        mem_free = 0
        for line in meminfo.split("\n"):
            if line.startswith("MemTotal:"):
                mem_total = int(line.split()[1]) / 1024  # KB to MB
            elif line.startswith("MemAvailable:"):
                mem_free = int(line.split()[1]) / 1024

        # Disk
        try:
            import shutil
            disk_free = shutil.disk_usage("/").free / (1024**3)
        except:
            disk_free = 0

        uptime_hours = float(uptime) / 3600

        territory = {
            "id": "ghojualamanchu_v3",
            "claimed": True,
            "status": "safe",
            "last_scan": datetime.now().isoformat(),
            "conditions": {
                "system_load": round(system_load, 2),
                "memory_available_mb": round(mem_free, 0),
                "disk_free_gb": round(disk_free, 2),
                "uptime_hours": round(uptime_hours, 1)
            }
        }

        # Threat assessment
        if system_load > 4.0:
            territory["status"] = "concerned"
        elif mem_free < 100:
            territory["status"] = "concerned"
        elif disk_free < 1:
            territory["status"] = "compromised"

        save_territory(territory)
        return territory

    except Exception as e:
        return {"status": "unknown", "error": str(e)}

def save_territory(territory):
    TERRITORY_FILE.write_text(json.dumps(territory, indent=2))

def load_territory():
    if TERRITORY_FILE.exists():
        return json.loads(TERRITORY_FILE.read_text())
    return DEFAULT_TERRITORY.copy()

def assess_threat(territory):
    """
    Convert territory status to numeric threat level (0.0–1.0).
    """
    status = territory.get("status", "safe")
    if status == "safe":
        return 0.0
    elif status == "monitored":
        return 0.2
    elif status == "concerned":
        return 0.6
    elif status == "compromised":
        return 0.9
    return 0.0

def process(signal):
    """
    Process signal through rcomplex.
    Reads: signal (for k_index if present)
    Writes: signal['rcomplex'] block
    Returns: modified signal
    """
    territory = scan_territory()
    threat_level = assess_threat(territory)

    signal["rcomplex"] = {
        "threat_detected": threat_level >= 0.6,
        "threat_level": round(threat_level, 3),
        "territory_status": territory.get("status", "safe"),
        "territory_conditions": territory.get("conditions", {}),
        "k_index": signal.get("rcomplex", {}).get("k_index", 0)  # Pass through
    }

    return signal
