"""NestDX configuration schema — dataclasses for nestdx.yaml."""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from enum import Enum

_DURATION_RE = re.compile(r"^\s*(\d+)\s*([hms]?)\s*$", re.IGNORECASE)


def parse_duration(value: str) -> int:
    """Convert a human-readable duration string to seconds.

    Supported formats: "4h", "30m", "90s", "120" (plain seconds).

    Raises:
        ValueError: If the string cannot be parsed.
    """
    match = _DURATION_RE.match(value)
    if not match:
        raise ValueError(
            f"Invalid duration '{value}'. Use a number with optional suffix: "
            "'h' (hours), 'm' (minutes), 's' (seconds). Examples: '4h', '30m', '90s'."
        )
    amount = int(match.group(1))
    unit = match.group(2).lower()
    if unit == "h":
        return amount * 3600
    if unit == "m":
        return amount * 60
    return amount


class ToolType(str, Enum):
    CLAUDE_CODE = "claude-code"
    CODEX = "codex"
    CURSOR = "cursor"
    HDX_AGENT = "hdx-agent"
    CUSTOM = "custom"


@dataclass
class ToolConfig:
    enabled: bool = True
    reason: str | None = None
    config: dict = field(default_factory=dict)
    agent_path: str | None = None


@dataclass
class SecretsPolicy:
    scan_agent_output: bool = True
    scan_commits: bool = True
    block_patterns: list[str] = field(
        default_factory=lambda: [
            r"AWS_SECRET_ACCESS_KEY\s*=\s*\S+",
            r"PRIVATE_KEY",
            r"password\s*=\s*\S+",
            r"Bearer\s+[A-Za-z0-9\-._~+/]{20,}",
            r"ghp_[A-Za-z0-9]{36}",
            r"sk-[A-Za-z0-9]{32,}",
        ]
    )
    custom_patterns_file: str | None = None


@dataclass
class FilesystemPolicy:
    read_only: list[str] = field(
        default_factory=lambda: [".env*", "secrets/", ".git/", "*.pem", "*.key"]
    )
    no_write: list[str] = field(default_factory=list)
    allowed_write: list[str] = field(default_factory=list)


@dataclass
class NetworkPolicy:
    """WALK phase — included in schema for forward compatibility."""

    allowed_domains: list[str] = field(default_factory=list)
    block_all_other_egress: bool = False


@dataclass
class ResourcePolicy:
    """WALK phase — included in schema for forward compatibility."""

    max_cpu: str | None = None
    max_memory: str | None = None
    max_session_duration: str | None = None


@dataclass
class Policies:
    secrets: SecretsPolicy = field(default_factory=SecretsPolicy)
    filesystem: FilesystemPolicy = field(default_factory=FilesystemPolicy)
    network: NetworkPolicy = field(default_factory=NetworkPolicy)
    resources: ResourcePolicy = field(default_factory=ResourcePolicy)


@dataclass
class EnvironmentConfig:
    """Container environment configuration for workspace isolation."""

    base: str = "python:3.13-slim"
    setup: list[str] = field(default_factory=list)
    test_command: str | None = None
    lint_command: str | None = None
    env_file: str | None = None
    dockerfile: str | None = None
    volumes: list[str] = field(default_factory=list)
    cache_dirs: list[str] = field(
        default_factory=lambda: ["~/.cache/uv", "~/.cache/pip", "node_modules"]
    )


@dataclass
class TrackingConfig:
    log_file_changes: bool = True
    log_commands: bool = True
    track_tokens: bool = True
    track_cost: bool = True
    session_dir: str = ".nestdx/sessions/"
    export_format: str = "json"


@dataclass
class NestConfig:
    name: str
    version: str = "0.1.0"
    tools: dict[str, ToolConfig] = field(default_factory=dict)
    policies: Policies = field(default_factory=Policies)
    tracking: TrackingConfig = field(default_factory=TrackingConfig)
    environment: EnvironmentConfig | None = None
