"""Server config generation — produces YAML for the agentsh server.

See spec Section 17 (17.1) for the ``generate_server_config()`` function.
"""

from __future__ import annotations

from typing import Any

import yaml

from agentsh_secure_sandbox.core.types import SecureConfig

# Default threat feeds when threat_feeds is None (not explicitly False)
_DEFAULT_FEEDS = [
    {
        "name": "urlhaus",
        "url": "https://urlhaus.abuse.ch/downloads/hostfile/",
        "format": "hostfile",
        "refresh_interval": "6h",
    },
    {
        "name": "phishing",
        "url": "https://raw.githubusercontent.com/elliotwutingfeng/Inversion-DNSBL-Blocklists/main/Google_hostfile/phishing-domains-ACTIVE.txt",
        "format": "domain-list",
        "refresh_interval": "12h",
    },
]

_DEFAULT_ALLOWLIST = [
    "github.com",
    "*.github.com",
    "registry.npmjs.org",
    "registry.yarnpkg.com",
    "pypi.org",
    "files.pythonhosted.org",
    "crates.io",
    "static.crates.io",
    "index.crates.io",
    "proxy.golang.org",
    "sum.golang.org",
]


def generate_server_config(config: SecureConfig) -> str:
    """Generate agentsh server config YAML from SecureConfig."""
    doc: dict[str, Any] = {
        "server": {"http": {"addr": "127.0.0.1:18080"}},
        "auth": {"type": "none"},
        "policies": {
            "system_dir": "/etc/agentsh/system",
            "dir": "/etc/agentsh",
            "default": config.policy_name,
        },
        "workspace": config.workspace,
        "sandbox": {
            "enabled": True,
            "allow_degraded": True,
        },
    }

    if config.real_paths is not None:
        doc["sandbox"]["real_paths"] = config.real_paths

    if config.enforce_redirects:
        doc["sandbox"]["enforce_redirects"] = True

    # Threat feeds: None = defaults, False = disabled, ThreatFeedsConfig = custom
    if config.threat_feeds is not False:
        tf = config.threat_feeds
        if tf is None:
            doc["threat_feeds"] = {
                "enabled": True,
                "action": "deny",
                "feeds": _DEFAULT_FEEDS,
                "allowlist": _DEFAULT_ALLOWLIST,
            }
        else:
            doc["threat_feeds"] = {
                "enabled": True,
                "action": tf.action,
                "feeds": [
                    {
                        "name": f.name,
                        "url": f.url,
                        "format": f.format,
                        "refresh_interval": f.refresh_interval,
                    }
                    for f in tf.feeds
                ],
            }
            if tf.allowlist is not None:
                doc["threat_feeds"]["allowlist"] = tf.allowlist

    if config.watchtower:
        doc["watchtower"] = {"url": config.watchtower}

    return yaml.dump(doc, default_flow_style=False, width=1000)
