import json
from pathlib import Path

CONFIG = Path.home() / ".coral8" / "config.json"
CONFIG.parent.mkdir(parents=True, exist_ok=True)
if not CONFIG.exists():
    CONFIG.write_text(json.dumps({}))

def _load_config():
    return json.loads(CONFIG.read_text())

def _save_config(cfg):
    CONFIG.write_text(json.dumps(cfg, indent=2))

def connect_file(path: str, alias: str = None) -> bool:
    cfg = _load_config()
    p = Path(path).resolve()
    alias = alias or p.stem
    if alias in cfg:
        print(f"⚠️  Alias '{alias}' already exists. Use a different alias or remove it first.")
        return False
    t = p.suffix.lower().lstrip(".")
    cfg[alias] = {"path": str(p), "type": t}
    _save_config(cfg)
    return True

def list_files():
    return _load_config()

