"""
config.py — Home directory setup and access.json management.
"""

import json
import os
from pathlib import Path
from datetime import datetime

# ─── Paths ────────────────────────────────────────────────────────────────────
HOME_DIR = Path.home() / ".onefirewall-ai"
SESSIONS_DIR = HOME_DIR / "sessions"
ACCESS_FILE = HOME_DIR / "access.json"
MEMORY_FILE = HOME_DIR / "MEMORY.md"
SOUL_FILE = HOME_DIR / "SOUL.md"

def get_session_file(session_id: str) -> Path:
    return SESSIONS_DIR / f"{session_id}.md"

# Default access structure
DEFAULT_ACCESS = {
    "endpoint": "",
    "api_key": "",
    "model": "openai/gpt-4o",
}

_SOUL_CONTENT = """\
# Soul

You are a helpful, concise, and knowledgeable AI assistant powered by the
OneFirewall AI Gateway. You reason carefully, admit uncertainty when needed,
and always aim to give accurate, practical answers.

> Edit this file to shape the persona of your AI agent.
"""

_MEMORY_CONTENT = """\
# Memory

<!-- The AI agent uses this file to remember things across sessions. -->
<!-- You can add persistent facts, preferences, or context here.     -->
"""

def create_session_file(session_id: str) -> None:
    path = get_session_file(session_id)
    if not path.exists():
        content = f"# Session: {session_id}\n_Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}_\n\n---\n\n"
        path.write_text(content)


def init_home() -> None:
    """Create ~/.onefirewall-ai/ and all default files on first run."""
    HOME_DIR.mkdir(parents=True, exist_ok=True)
    SESSIONS_DIR.mkdir(parents=True, exist_ok=True)

    if not ACCESS_FILE.exists():
        ACCESS_FILE.write_text(json.dumps(DEFAULT_ACCESS, indent=2))

    if not MEMORY_FILE.exists():
        MEMORY_FILE.write_text(_MEMORY_CONTENT)

    if not SOUL_FILE.exists():
        SOUL_FILE.write_text(_SOUL_CONTENT)


def load_access() -> dict:
    """Load access.json. Returns defaults if file is missing/corrupt."""
    init_home()
    try:
        data = json.loads(ACCESS_FILE.read_text())
        return {**DEFAULT_ACCESS, **data}
    except Exception:
        return dict(DEFAULT_ACCESS)


def save_access(data: dict) -> None:
    """Persist updated access.json."""
    init_home()
    ACCESS_FILE.write_text(json.dumps(data, indent=2))


def is_logged_in() -> bool:
    """Return True if endpoint and api_key are configured."""
    acc = load_access()
    return bool(acc.get("endpoint") and acc.get("api_key"))
