import csv
import time
import json
import urllib.request
import tiktoken

# Local Ollama Configuration
OLLAMA_URL = "http://localhost:11434/api/generate"
OLLAMA_MODEL = "llama3"

tokenizer = tiktoken.get_encoding("cl100k_base")


class TCADARERouter:
    """Layer 1: Task Complexity Evaluator & Router."""

    def __init__(self, tau_1: float = 30.0, tau_2: float = 70.0):
        self.tau_1 = tau_1
        self.tau_2 = tau_2
        self.weights = [0.25, 0.25, 0.25, 0.25]

    def extract_features(self, query: str) -> dict:
        tokens = tokenizer.encode(query)
        f_len = min(len(tokens) / 100.0, 1.0) * 100.0

        academic_keywords = [
            "gpt", "llama", "arxiv", "agent", "metagpt",
            "react", "benchmark", "dataset", "transformer"
        ]
        f_ent = min(sum(1 for kw in academic_keywords if kw in query.lower()) * 20.0, 100.0)

        hop_indicators = [
            "compare", "difference", "between", "relate",
            "why", "how do", "across"
        ]
        f_hop = 100.0 if any(ind in query.lower() for ind in hop_indicators) else 10.0

        syn_indicators = [
            "synthesize", "survey", "review", "comprehensive",
            "all papers", "summarize"
        ]
        f_syn = 100.0 if any(ind in query.lower() for ind in syn_indicators) else 10.0

        return {"f_len": f_len, "f_ent": f_ent, "f_hop": f_hop, "f_syn": f_syn}

    def compute_complexity(self, features: dict) -> float:
        return sum(self.weights[i] * list(features.values())[i] for i in range(4))

    def route_query(self, query: str) -> tuple:
        features = self.extract_features(query)
        c_score = self.compute_complexity(features)
        if c_score < self.tau_1:
            return "Route_C1_Single_Agent", c_score
        elif self.tau_1 <= c_score < self.tau_2:
            return "Route_C2_Dual_Pipeline", c_score
        else:
            return "Route_C3_Full_Orchestration", c_score


class OllamaAgentExecutionEngine:
    """Layer 2 & 4: Specialist Agent Execution & Telemetry Capture."""

    @staticmethod
    def call_agent(agent_role: str, query: str, context: str = "") -> tuple:
        t_start = time.time()
        prompt_text = (
            f"You are agent role: {agent_role}.\n"
            f"Query: {query}\n"
            f"Context: {context}\n"
            f"Provide a concise academic response."
        )
        prompt_tokens = len(tokenizer.encode(prompt_text))

        payload = {"model": OLLAMA_MODEL, "prompt": prompt_text, "stream": False}
        try:
            req = urllib.request.Request(
                OLLAMA_URL,
                data=json.dumps(payload).encode("utf-8"),
                headers={"Content-Type": "application/json"}
            )
            with urllib.request.urlopen(req) as response:
                result = json.loads(response.read().decode("utf-8"))
                response_text = result.get("response", "")
        except Exception:
            response_text = f"[{agent_role} Local Output Processed]"

        completion_tokens = len(tokenizer.encode(response_text))
        total_tokens = prompt_tokens + completion_tokens
        elapsed_latency = time.time() - t_start

        telemetry = {
            "tokens": total_tokens,
            "cost": 0.00000,
            "latency": round(elapsed_latency, 2),
            "calls": 1
        }
        return response_text, telemetry


def run_pipeline_experiment(query: str) -> dict:
    """End-to-end TCA-DARE execution pipeline."""
    router = TCADARERouter()
    route, score = router.route_query(query)
    total_tokens, total_cost, total_latency, total_calls = 0, 0.0, 0.0, 0

    if route == "Route_C1_Single_Agent":
        _, tel = OllamaAgentExecutionEngine.call_agent("A_ext", query)
        total_tokens += tel["tokens"]
        total_cost += tel["cost"]
        total_latency += tel["latency"]
        total_calls += tel["calls"]
    elif route == "Route_C2_Dual_Pipeline":
        docs, t1 = OllamaAgentExecutionEngine.call_agent("A_src", query)
        draft, t2 = OllamaAgentExecutionEngine.call_agent("A_syn", query, context=docs)
        _, t3 = OllamaAgentExecutionEngine.call_agent("A_chk", draft, context=docs)
        for t in [t1, t2, t3]:
            total_tokens += t["tokens"]
            total_cost += t["cost"]
            total_latency += t["latency"]
            total_calls += t["calls"]
    else:
        agents = ["A_src", "A_ext", "A_aud", "A_syn", "A_chk"]
        context_data = ""
        for agent in agents:
            res, tel = OllamaAgentExecutionEngine.call_agent(agent, query, context=context_data)
            context_data += " " + res
            total_tokens += tel["tokens"]
            total_cost += tel["cost"]
            total_latency += tel["latency"]
            total_calls += tel["calls"]

    return {
        "Route": route,
        "Complexity_Score": round(score, 2),
        "Total_Tokens": total_tokens,
        "Total_Cost": total_cost,
        "Total_Latency": round(total_latency, 2),
        "Total_Calls": total_calls
    }


if __name__ == "__main__":
    sample_queries = [
        "What is the parameter size of Llama 3?",
        "Compare the reasoning mechanisms between ReAct and Reflexion across agent benchmarks.",
        "Synthesize a comprehensive literature review across all papers on multi-agent LLM orchestration protocols including MCP, ACP, A2A, and ANP."
    ]
    for q in sample_queries:
        print(run_pipeline_experiment(q))