
import json
import time

class DarwinianScalingSkill:
    """
    Implements the 'Test Template -> Scaled Profit' logic.
    Each sub-account starts as a 'Mutation' (Test).
    Successful (profitable) mutations get 'Scaled'.
    """
    
    def __init__(self, ghl_bridge):
        self.bridge = ghl_bridge
        self.sales_threshold = 1  # Minimum 1 sale to consider 'proven'
        self.scaling_multiplier = 3.0 # Aggressive resource increase for proven nodes

    def evaluate_sub_account(self, location_id: str):
        """
        Audits a sub-account for profitability and decides whether to scale, 
        maintain, or prune (Fail-Fast).
        """
        print(f"🧬 [Darwin] Evaluating node: {location_id}")
        
        # 1. Fetch Sales Data (Market-Driven Selection)
        sales_count = self._get_sales_count(location_id)
        print(f"   🛒 Total Customers: {sales_count}")

        # 2. Check for Human Perception Override (Test Customer Zero)
        if self._has_positive_human_feedback(location_id):
            print(f"   👤 HUMAN VALIDATED. User (Customer Zero) approved this mutation. Scaling.")
            return self._scale_node(location_id)

        if sales_count >= self.sales_threshold:
            print(f"   🏆 MARKET VALIDATED. Node is successful. Scaling.")
            return self._scale_node(location_id)
        else:
            print(f"   ⚖️ TESTING PHASE. No sales/feedback yet. Continuous optimization.")
            return "testing"

    def _has_positive_human_feedback(self, location_id: str) -> bool:
        """
        Checks human_feedback.json for USER approval.
        """
        import json
        path = "E:/genesis-system/data/human_feedback.json"
        if not os.path.exists(path):
            return False
            
        try:
            with open(path, "r") as f:
                data = json.load(f)
                for entry in data.get("feedback", []):
                    if entry["location_id"] == location_id and entry["status"] == "approved":
                        return True
        except:
            pass
        return False

    def _get_sales_count(self, location_id: str) -> int:
        """
        Audits GHL for successful payments/invoices representing a 'Purchase'.
        """
        # In production: call_tool("get_payments", {"locationId": location_id, "status": "succeeded"})
        return 0 # Placeholder

    def _scale_node(self, location_id: str):
        """
        Increases automation frequency and outreach budget for a node.
        """
        # Logic: 
        # 1. Add 'Scaled' tag in GHL
        # 2. Increase n8n workflow trigger frequency
        # 3. Increase Vapi minute allocation
        print(f"   ✨ Scaling operations for {location_id}...")
        return "scaled"

if __name__ == "__main__":
    print("Darwinian Scaling Skill Active. Awaiting Revenue Pulse.")
