"""Konfigurasi agent. Disimpan di %ProgramData%\\ClassroomAgent (hanya SYSTEM & Administrators yang boleh membaca token)."""
from __future__ import annotations

import json
import os
import uuid
from dataclasses import asdict, dataclass, field
from pathlib import Path

VERSION = "1.0.0"
IPC_PORT = 47653  # hanya 127.0.0.1


def agent_home() -> Path:
    env = os.environ.get("CMS_AGENT_HOME")
    if env:
        p = Path(env)
    elif os.name == "nt":
        p = Path(os.environ.get("PROGRAMDATA", r"C:\ProgramData")) / "ClassroomAgent"
    else:
        p = Path.home() / ".classroom-agent"
    p.mkdir(parents=True, exist_ok=True)
    return p


@dataclass
class Config:
    server_url: str = ""
    ca_file: str = ""  # sertifikat server (self-signed) yang dipercaya agent
    device_uid: str = ""
    token: str = ""
    signing_key: str = ""
    computer_id: int = 0
    dry_run: bool = False
    chrome_port: int = 9333
    edge_port: int = 9334
    protect_task_manager: bool = False
    applocker: bool = False  # aktifkan hanya pada Windows Enterprise/Education
    token_issued_at: float = 0.0
    extra: dict = field(default_factory=dict)

    @property
    def path(self) -> Path:
        return agent_home() / "config.json"

    @classmethod
    def load(cls) -> "Config":
        p = agent_home() / "config.json"
        if p.exists():
            d = json.loads(p.read_text(encoding="utf-8"))
            return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})
        return cls(device_uid=str(uuid.uuid4()))

    def save(self) -> None:
        if not self.device_uid:
            self.device_uid = str(uuid.uuid4())
        tmp = self.path.with_suffix(".tmp")
        tmp.write_text(json.dumps(asdict(self), indent=2), encoding="utf-8")
        os.replace(tmp, self.path)

    @property
    def verify(self):
        return self.ca_file if self.ca_file and Path(self.ca_file).exists() else True

    @property
    def ws_url(self) -> str:
        return self.server_url.replace("https://", "wss://").replace("http://", "ws://").rstrip("/") + "/ws/agent"
