import json
from pathlib import Path

CONTEXT_FILE = Path.home() / ".acemist/.acemist_cli_context.json"

class CLIContext:
    def __init__(self):
        self.data = self._load()

    def _load(self):
        if CONTEXT_FILE.exists():
            with open(CONTEXT_FILE) as f:
                content = f.read().strip()
                if not content:
                    return {}
                return json.loads(content)
        return {}

    def save(self):
        CONTEXT_FILE.parent.mkdir(parents=True, exist_ok=True)
        with open(CONTEXT_FILE, "w") as f:
            json.dump(self.data, f, indent=4)

    def set_context(self, name: str, region, api_token: str, org_id: str | None = None, org_name: str | None = None, site_id: str|None=None):
        apiurl = f"https://{region.api_url}/api/v1"
        ctxs = self.data.setdefault("contexts", {})
        ctxs[name] = {
            "apiurl": apiurl,
            "region": region.value,
            "api_token": api_token,
            
        }
        
        if org_id:
            ctxs[name]["org_id"] = org_id
        if org_name:
            ctxs[name]["org_name"] = org_name
        if site_id:
            ctxs[name]["site_id"]=site_id
        self.data["active_context"] = name
        self.save()

    def update_org(self, org_id: str, org_name: str):
        """Set org_id and org_name on the active context."""
        ctx = self.get_active_context()
        if ctx is not None:
            ctx["org_id"] = org_id
            ctx["org_name"] = org_name
            self.save()

    def set_active(self, name: str):
        self.data["active_context"] = name
        self.save()

    def get_active_context(self):
        name = self.data.get("active_context")
        return self.data.get("contexts", {}).get(name)

    def get_active_url(self):
        ctx = self.get_active_context()
        return ctx.get("apiurl") if ctx else None

    def get_active_org_id(self) -> str | None:
        ctx = self.get_active_context()
        return ctx.get("org_id") if ctx else None
