from __future__ import annotations

import json
import os
import uuid
from pathlib import Path
from typing import Optional, Tuple


DEFAULT_IDENTITY_FILENAME = "agent_identity.json"


def _resolve_identity_path(log_dir: Optional[str], agent_key: Optional[str]) -> Path:
    base = Path(log_dir) if log_dir else Path.home() / ".causum" / "agent"
    if agent_key:
        base = base / agent_key
    return base / DEFAULT_IDENTITY_FILENAME


def load_or_create_instance_id(
    log_dir: Optional[str],
    configured_id: Optional[str] = None,
    agent_key: Optional[str] = None,
) -> Tuple[str, Path]:
    """
    Return a stable instance_id, generating and persisting it if missing.
    If configured_id is provided, it is used and persisted to the identity file.
    """
    identity_path = _resolve_identity_path(log_dir, agent_key)
    instance_id = (configured_id or "").strip() or None

    if not instance_id and identity_path.exists():
        try:
            data = json.loads(identity_path.read_text())
            if isinstance(data, dict) and data.get("instance_id"):
                instance_id = str(data["instance_id"])
        except Exception:
            pass

    if not instance_id:
        instance_id = str(uuid.uuid4())

    try:
        identity_path.parent.mkdir(parents=True, exist_ok=True)
        try:
            os.chmod(identity_path.parent, 0o700)
        except OSError:
            pass
        identity_path.write_text(json.dumps({"instance_id": instance_id}))
        try:
            os.chmod(identity_path, 0o600)
        except OSError:
            pass
    except Exception:
        # Persistence failure should not block startup; agent will regenerate next run if needed.
        pass

    return instance_id, identity_path
