from __future__ import annotations

import json
import os
from pathlib import Path


DEFAULT_CONFIG: dict[str, object] = {
    "log_source": "local_syslog",
    "graylog_mcp_url": "",
    "graylog_stream": "",
    "graylog_streams": [],
    "graylog_stream_profiles": [],
    "graylog_query": "*",
    "graylog_field_mapping": "",
    "llm_enabled": False,
    "llm_model": "",
    "threat_intel_enabled": False,
}

EDITABLE_FIELDS = set(DEFAULT_CONFIG) | {"graylog_mcp_token"}


class ConfigStore:
    def __init__(self, path: str) -> None:
        self.path = Path(path)

    def read(self) -> dict[str, object]:
        try:
            stored = json.loads(self.path.read_text(encoding="utf-8"))
        except (FileNotFoundError, json.JSONDecodeError, OSError):
            stored = {}
        return {**DEFAULT_CONFIG, **{key: value for key, value in stored.items() if key in EDITABLE_FIELDS}}

    def public(self) -> dict[str, object]:
        config = self.read()
        config["graylog_mcp_token_configured"] = bool(config.pop("graylog_mcp_token", ""))
        return config

    def update(self, values: dict[str, object]) -> dict[str, object]:
        current = self.read()
        for key, value in values.items():
            if key not in EDITABLE_FIELDS:
                continue
            if key == "graylog_mcp_token" and value == "":
                continue
            if key in {"llm_enabled", "threat_intel_enabled"}:
                current[key] = bool(value)
            elif key == "log_source" and value in {"local_syslog", "graylog_mcp"}:
                current[key] = value
            elif key == "graylog_streams" and isinstance(value, list):
                current[key] = [
                    {"id": str(item.get("id", "")), "title": str(item.get("title", "")), "enabled": bool(item.get("enabled"))}
                    for item in value if isinstance(item, dict) and item.get("id")
                ]
            elif key == "graylog_stream_profiles" and isinstance(value, list):
                current[key] = [item for item in value if isinstance(item, dict) and item.get("stream_id")]
            elif isinstance(value, str):
                current[key] = value.strip()
        self.path.parent.mkdir(parents=True, exist_ok=True)
        temporary = self.path.with_suffix(".tmp")
        temporary.write_text(json.dumps(current, indent=2, sort_keys=True), encoding="utf-8")
        os.chmod(temporary, 0o600)
        temporary.replace(self.path)
        return self.public()
