"""Code patterns for detecting AISA layer coverage in agentic AI projects.

Each pattern maps file content signatures (imports, function calls, config keys)
to AISA criteria, enabling automatic coverage detection via code scanning.
"""

from dataclasses import dataclass


@dataclass
class Pattern:
    """A code pattern that indicates coverage of an AISA criterion."""
    criterion_id: str
    description: str
    # Any of these strings found in source code counts as a match
    signatures: list[str]
    # Boost score if multiple signatures match
    confidence_boost: float = 0.0


# ---------------------------------------------------------------------------
# L1: LLM Foundation Layer
# ---------------------------------------------------------------------------

L1_PATTERNS = [
    Pattern(
        "L1.1", "Multiple LLM provider support",
        [
            "from langchain", "from llama_index", "import anthropic",
            "import openai", "from openai", "import google.generativeai",
            "ChatOpenAI", "ChatAnthropic", "ChatGoogle", "Ollama",
            "AzureChatOpenAI", "BedrockChat", "from litellm",
            "import litellm", "ChatVertexAI", "from semantic_kernel",
            "GenAiModel", "LlmAgent",
        ],
    ),
    Pattern(
        "L1.2", "Prompt templates",
        [
            "PromptTemplate", "ChatPromptTemplate", "FewShotPromptTemplate",
            "SystemMessage", "HumanMessage", "system_prompt",
            "prompt_template", "instruction_template", "jinja2",
            "f-string", ".format(", "ChatHistory",
            "KernelFunction", "kernel_function",
        ],
    ),
    Pattern(
        "L1.3", "Context window management",
        [
            "max_tokens", "token_limit", "truncat", "context_window",
            "TokenTextSplitter", "SentenceSplitter", "ConversationSummaryMemory",
            "truncation_strategy", "token_count", "num_tokens",
            "prompt_caching", "cache_control",
        ],
    ),
    Pattern(
        "L1.4", "Safety filters and grounding",
        [
            "safety_filter", "content_filter", "moderation", "guardrail",
            "safety_settings", "HarmCategory", "HarmBlockThreshold",
            "constitutional_ai", "refusal", "grounding",
            "NeMoGuardrails", "guardrails_ai", "lakera",
        ],
    ),
    Pattern(
        "L1.5", "Fine-tuning and alignment",
        [
            "fine_tun", "rlhf", "alignment", "instruction_tuning",
            "peft", "lora", "qlora", "sft_trainer", "dpo",
            "reward_model",
        ],
    ),
    Pattern(
        "L1.6", "Structured outputs",
        [
            "output_parser", "PydanticOutputParser", "JsonOutputParser",
            "structured_output", "response_format", "json_schema",
            "with_structured_output", "function_call", "tool_choice",
        ],
    ),
]

# ---------------------------------------------------------------------------
# L2: Tool & Environment Layer
# ---------------------------------------------------------------------------

L2_PATTERNS = [
    Pattern(
        "L2.1", "Tool definitions",
        [
            "@tool", "StructuredTool", "BaseTool", "FunctionTool",
            "tool_definition", "tools=[", "function_declarations",
            "@kernel_function", "ToolSpec", "QueryEngineTool",
            "register_function", "AssistantAgent",
        ],
    ),
    Pattern(
        "L2.2", "Schema validation",
        [
            "BaseModel", "pydantic", "Field(", "json_schema",
            "input_schema", "args_schema", "validator",
            "model_validator", "field_validator",
        ],
    ),
    Pattern(
        "L2.3", "Sandboxing",
        [
            "sandbox", "docker", "container", "isolated",
            "DockerCommandLineCodeExecutor", "code_interpreter",
            "subprocess", "RestrictedPython", "seccomp",
            "CodeExecutionConfig",
        ],
    ),
    Pattern(
        "L2.4", "Permission controls",
        [
            "permission", "allow_list", "deny_list", "allowedTools",
            "disallowedTools", "scope", "authorization",
            "access_control", "capability", "rbac",
        ],
    ),
    Pattern(
        "L2.5", "MCP support",
        [
            "mcp", "model_context_protocol", "MCPServer",
            "MCPClient", "McpToolSpec", "mcp_server",
            "langchain_mcp", "MCPServerAdapter",
        ],
    ),
    Pattern(
        "L2.6", "Error handling and retries",
        [
            "retry", "max_retries", "backoff", "ToolException",
            "error_handling", "fallback", "circuit_breaker",
            "tenacity", "RetryAgentWorker", "on_error",
        ],
    ),
    Pattern(
        "L2.7", "Rate limiting",
        [
            "rate_limit", "throttle", "requests_per_minute",
            "RateLimiter", "token_bucket", "rpm", "tpm",
            "concurrency_limit",
        ],
    ),
]

# ---------------------------------------------------------------------------
# L3: Cognitive Agent Layer
# ---------------------------------------------------------------------------

L3_PATTERNS = [
    Pattern(
        "L3.1", "Task planning and decomposition",
        [
            "plan", "planner", "decompos", "sub_task", "subtask",
            "PlanAndExecute", "StepwisePlanner", "SequentialPlanner",
            "SubQuestionQueryEngine", "task_decomposition",
            "planning=True", "hierarchical",
        ],
    ),
    Pattern(
        "L3.2", "Multi-turn reasoning",
        [
            "chat_history", "ChatHistory", "conversation",
            "multi_turn", "ConversationChain", "thread",
            "messages", "AgentExecutor", "agentic_loop",
        ],
    ),
    Pattern(
        "L3.3", "Memory management",
        [
            "memory", "ConversationBufferMemory", "ConversationSummaryMemory",
            "VectorStoreMemory", "EntityMemory", "long_term_memory",
            "episodic_memory", "MemoryService", "chat_memory",
            "ChatMemoryBuffer", "remember", "memory_store",
        ],
    ),
    Pattern(
        "L3.4", "Goal tracking",
        [
            "goal", "objective", "target", "expected_output",
            "success_criteria", "task_complete", "termination",
            "goal_tracking", "milestone",
        ],
    ),
    Pattern(
        "L3.5", "Reflection loops",
        [
            "reflect", "self_critique", "self_eval", "reflexion",
            "critique", "improve", "feedback_loop", "self_check",
            "SocietyOfMind", "inner_monologue",
        ],
    ),
    Pattern(
        "L3.6", "External feedback integration",
        [
            "human_input", "user_feedback", "feedback",
            "human_in_the_loop", "approval", "UserProxyAgent",
            "HumanInputRun", "interrupt", "ask_human",
        ],
    ),
]

# ---------------------------------------------------------------------------
# L4: Agentic Infrastructure Layer
# ---------------------------------------------------------------------------

L4_PATTERNS = [
    Pattern(
        "L4.1", "Workflow orchestration",
        [
            "StateGraph", "workflow", "pipeline", "DAG",
            "SequentialAgent", "ParallelAgent", "LoopAgent",
            "RoundRobinGroupChat", "SelectorGroupChat",
            "Crew", "Process", "Flow", "langgraph",
            "Workflow", "step", "orchestrat",
        ],
    ),
    Pattern(
        "L4.2", "State management",
        [
            "state", "checkpoint", "persist", "save_state",
            "load_state", "session_state", "MemorySaver",
            "SqliteSaver", "RedisSaver", "checkpointer",
        ],
    ),
    Pattern(
        "L4.3", "Multi-agent coordination",
        [
            "multi_agent", "agent_team", "crew", "group_chat",
            "delegate", "handoff", "supervisor", "swarm",
            "ConcurrentAgent", "agent_to_agent",
        ],
    ),
    Pattern(
        "L4.4", "Observability and tracing",
        [
            "trace", "span", "opentelemetry", "otel",
            "langsmith", "LangSmith", "arize", "phoenix",
            "langfuse", "Langfuse", "tracing", "Cloud Trace",
            "CallbackManager", "instrument",
        ],
    ),
    Pattern(
        "L4.5", "Logging and monitoring",
        [
            "logging", "logger", "log_level", "monitor",
            "dashboard", "alert", "metric", "prometheus",
            "grafana", "datadog", "structured_log",
        ],
    ),
    Pattern(
        "L4.6", "Agent lifecycle management",
        [
            "agent_lifecycle", "spawn", "terminate", "scale",
            "agent_pool", "lifecycle", "create_agent",
            "destroy_agent", "agent_registry",
        ],
    ),
    Pattern(
        "L4.7", "Latency and cost optimization",
        [
            "cache", "batch", "caching", "LRUCache",
            "redis_cache", "memoize", "concurrent",
            "async", "parallel", "optimization",
        ],
    ),
]

# ---------------------------------------------------------------------------
# L5: Evaluation & Feedback Layer
# ---------------------------------------------------------------------------

L5_PATTERNS = [
    Pattern(
        "L5.1", "Component-level evaluation",
        [
            "eval", "evaluate", "test_prompt", "test_tool",
            "evaluator", "FaithfulnessEvaluator", "RelevancyEvaluator",
            "CorrectnessEvaluator", "criteria_eval", "adk eval",
        ],
    ),
    Pattern(
        "L5.2", "Trajectory-level evaluation",
        [
            "trajectory", "end_to_end", "e2e_test", "scenario_test",
            "multi_step_eval", "agent_eval", "benchmark",
            "BatchEvalRunner", "run_evaluation",
        ],
    ),
    Pattern(
        "L5.3", "Behavioral monitoring",
        [
            "drift", "anomaly", "behavioral_monitor", "alert",
            "regression_detect", "canary_eval", "shadow_eval",
            "live_monitor",
        ],
    ),
    Pattern(
        "L5.4", "Regression testing",
        [
            "regression", "pytest", "unittest", "test_suite",
            "golden_test", "snapshot_test", "baseline_test",
            "assert", "expected_output",
        ],
    ),
    Pattern(
        "L5.5", "Human-in-the-loop evaluation",
        [
            "human_eval", "annotation", "labeling", "review",
            "human_feedback", "rating", "thumbs_up",
            "preference", "rlhf_eval",
        ],
    ),
    Pattern(
        "L5.6", "Quality metrics",
        [
            "accuracy", "precision", "recall", "f1_score",
            "bleu", "rouge", "faithfulness", "relevancy",
            "quality_metric", "score",
        ],
    ),
]

# ---------------------------------------------------------------------------
# L6: Development & Deployment Layer
# ---------------------------------------------------------------------------

L6_PATTERNS = [
    Pattern(
        "L6.1", "Version control of agents",
        [
            "version", "agent_version", "prompt_version",
            "model_version", "artifact", "manifest",
            "agent_config", "versioned",
        ],
    ),
    Pattern(
        "L6.2", "CI/CD integration",
        [
            "ci_cd", "github_actions", "gitlab_ci", "jenkins",
            ".github/workflows", "pipeline", "deploy",
            "Dockerfile", "docker-compose",
        ],
    ),
    Pattern(
        "L6.3", "A/B testing",
        [
            "ab_test", "a_b_test", "experiment", "variant",
            "traffic_split", "feature_flag", "rollout",
        ],
    ),
    Pattern(
        "L6.4", "Performance benchmarking",
        [
            "benchmark", "latency_test", "perf_test",
            "load_test", "stress_test", "throughput",
            "p50", "p95", "p99",
        ],
    ),
    Pattern(
        "L6.5", "Staged rollout",
        [
            "canary", "blue_green", "staged", "rollback",
            "gradual_rollout", "shadow_deploy",
        ],
    ),
    Pattern(
        "L6.6", "Secrets management",
        [
            "secret", "vault", "env_var", "dotenv",
            "load_dotenv", "os.environ", "getenv",
            "api_key", "credential", "keyring",
        ],
    ),
    Pattern(
        "L6.7", "Model lifecycle tracking",
        [
            "mlflow", "wandb", "weights_and_biases",
            "experiment_tracking", "model_registry",
            "model_card", "artifact_store",
        ],
    ),
]

# ---------------------------------------------------------------------------
# L7: Governance, Ethics & Policy Layer
# ---------------------------------------------------------------------------

L7_PATTERNS = [
    Pattern(
        "L7.1", "Policy-as-code",
        [
            "policy", "rule_engine", "opa", "open_policy_agent",
            "policy_check", "enforce_policy", "constraint",
            "governance_rule",
        ],
    ),
    Pattern(
        "L7.2", "Privacy and data protection",
        [
            "pii", "redact", "anonymize", "gdpr", "data_protection",
            "privacy", "encrypt", "mask", "scrub",
            "personally_identifiable",
        ],
    ),
    Pattern(
        "L7.3", "Fairness and bias mitigation",
        [
            "fairness", "bias", "equit", "demographic",
            "protected_attribute", "disparate_impact",
            "fairlearn", "aif360",
        ],
    ),
    Pattern(
        "L7.4", "Accountability framework",
        [
            "audit", "audit_log", "audit_trail", "accountability",
            "ownership", "escalation", "incident", "responsible",
        ],
    ),
    Pattern(
        "L7.5", "Human oversight",
        [
            "human_oversight", "approval_gate", "review_required",
            "human_approval", "escalate_to_human", "override",
            "intervention", "supervisor_approval",
        ],
    ),
    Pattern(
        "L7.6", "Regulatory compliance",
        [
            "compliance", "regulation", "hipaa", "sox", "soc2",
            "iso_27001", "nist", "ai_rmf", "eu_ai_act",
        ],
    ),
    Pattern(
        "L7.7", "Explainability",
        [
            "explain", "interpretab", "reasoning_trace",
            "decision_log", "rationale", "thinking",
            "chain_of_thought", "transparency",
        ],
    ),
]

# ---------------------------------------------------------------------------
# Cross-Layer Contract Patterns
# ---------------------------------------------------------------------------

C1_PATTERNS = [
    Pattern("C1.1", "Cross-layer policy propagation",
            ["policy_engine", "global_policy", "cross_layer", "policy_propagat"]),
    Pattern("C1.2", "Tool allowlists/denylists",
            ["allow_list", "deny_list", "allowedTools", "disallowedTools", "tool_filter"]),
    Pattern("C1.3", "Data classification rules",
            ["classification", "data_label", "sensitivity", "confidential", "restricted"]),
]

C2_PATTERNS = [
    Pattern("C2.1", "End-to-end trace IDs",
            ["trace_id", "correlation_id", "request_id", "run_id", "span_id"]),
    Pattern("C2.2", "Structured action logs",
            ["action_log", "tool_log", "decision_log", "structured_log", "event_log"]),
    Pattern("C2.3", "OpenTelemetry compatibility",
            ["opentelemetry", "otel", "TracerProvider", "SpanExporter", "OTLPSpanExporter"]),
]

C3_PATTERNS = [
    Pattern("C3.1", "Agent package versioning",
            ["agent_version", "package_version", "manifest", "agent_manifest"]),
    Pattern("C3.2", "Prompt and tool versioning",
            ["prompt_version", "tool_version", "schema_version", "template_version"]),
    Pattern("C3.3", "Reproducible runs",
            ["seed", "deterministic", "reproducible", "snapshot", "pinned_version"]),
]

C4_PATTERNS = [
    Pattern("C4.1", "Token budget enforcement",
            ["token_budget", "max_tokens", "token_limit", "token_cap"]),
    Pattern("C4.2", "Cost ceiling controls",
            ["cost_limit", "cost_cap", "budget_limit", "spend_limit", "max_cost"]),
    Pattern("C4.3", "Action budget limits",
            ["max_iterations", "max_steps", "max_turns", "action_limit", "max_retries"]),
]

# ---------------------------------------------------------------------------
# All patterns grouped by layer/contract ID
# ---------------------------------------------------------------------------

ALL_PATTERNS: dict[str, list[Pattern]] = {
    "L1": L1_PATTERNS,
    "L2": L2_PATTERNS,
    "L3": L3_PATTERNS,
    "L4": L4_PATTERNS,
    "L5": L5_PATTERNS,
    "L6": L6_PATTERNS,
    "L7": L7_PATTERNS,
    "C1": C1_PATTERNS,
    "C2": C2_PATTERNS,
    "C3": C3_PATTERNS,
    "C4": C4_PATTERNS,
}
