"""
Pawprint Data Layer

JSON file storage (future: MongoDB)
"""

import json
from pathlib import Path
from typing import List, Optional

# Add parent to path for models import
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))

from models.pydantic import (
    Vein, Nest, Larder, Template, Tool,
    Pulse, Book, Table,
    VeinCollection, NestCollection, LarderCollection,
    TemplateCollection, ToolCollection,
    PulseCollection, BookCollection, TableCollection,
    Status
)

DATA_DIR = Path(__file__).parent.resolve()

# Debug: print data dir on import
print(f"[data] DATA_DIR: {DATA_DIR}")
print(f"[data] DATA_DIR exists: {DATA_DIR.exists()}")
print(f"[data] veins.json exists: {(DATA_DIR / 'veins.json').exists()}")


def _load_json(filename: str) -> dict:
    filepath = DATA_DIR / filename
    if filepath.exists():
        with open(filepath) as f:
            data = json.load(f)
            print(f"[data] Loaded {filename}: {len(data.get('items', []))} items")
            return data
    print(f"[data] File not found: {filepath}")
    return {"items": []}


def _save_json(filename: str, data: dict):
    filepath = DATA_DIR / filename
    with open(filepath, 'w') as f:
        json.dump(data, f, indent=2)


# === Loaders ===

def get_veins() -> List[Vein]:
    data = _load_json("veins.json")
    return VeinCollection(**data).items


def get_nests() -> List[Nest]:
    data = _load_json("nests.json")
    return NestCollection(**data).items


def get_larders() -> List[Larder]:
    data = _load_json("larders.json")
    return LarderCollection(**data).items


def get_templates() -> List[Template]:
    data = _load_json("templates.json")
    return TemplateCollection(**data).items


def get_tools() -> List[Tool]:
    data = _load_json("tools.json")
    return ToolCollection(**data).items


def get_cabinets() -> list:
    """Load cabinets (simple dict, no pydantic yet)."""
    data = _load_json("cabinets.json")
    return data.get("items", [])


def get_monitors() -> list:
    """Load monitors (simple dict, no pydantic yet)."""
    data = _load_json("monitors.json")
    return data.get("items", [])


def get_pulses() -> List[Pulse]:
    data = _load_json("pulses.json")
    return PulseCollection(**data).items


def get_books() -> List[Book]:
    data = _load_json("books.json")
    return BookCollection(**data).items


def get_tables() -> List[Table]:
    data = _load_json("tables.json")
    return TableCollection(**data).items


# === Helpers ===

def get_vein(name: str) -> Optional[Vein]:
    for v in get_veins():
        if v.name == name:
            return v
    return None


def get_nest(name: str) -> Optional[Nest]:
    for n in get_nests():
        if n.name == name:
            return n
    return None


def get_larder(name: str) -> Optional[Larder]:
    for l in get_larders():
        if l.name == name:
            return l
    return None


# === For frontend rendering ===

def get_artery_data() -> dict:
    """Data for artery frontend."""
    return {
        "veins": [v.model_dump() for v in get_veins()],
        "nests": [n.model_dump() for n in get_nests()],
        "larders": [l.model_dump() for l in get_larders()],
        "pulses": [p.model_dump() for p in get_pulses()],
    }


def get_album_data() -> dict:
    """Data for album frontend."""
    return {
        "templates": [t.model_dump() for t in get_templates()],
        "larders": [l.model_dump() for l in get_larders()],
        "books": [b.model_dump() for b in get_books()],
    }


def get_ward_data() -> dict:
    """Data for ward frontend."""
    return {
        "tools": [t.model_dump() for t in get_tools()],
        "monitors": get_monitors(),
        "cabinets": get_cabinets(),
        "nests": [n.model_dump() for n in get_nests()],
        "larders": [l.model_dump() for l in get_larders()],
        "tables": [t.model_dump() for t in get_tables()],
    }
