"""
GitMem Coding - Coding Context API

Simplified High-level API for code flow management.
Provides exactly 4 CRUD operations to manage the Code Flow structure.
"""

from typing import Dict, Any, List
from .coding_store import CodingContextStore
import os

class CodingAPI:
    """
    High-level API for coding context storage.
    
    Exposes only 4 core CRUD operations:
    1. create_flow(file_path)
    2. get_flow(query)
    3. update_flow(file_path)
    4. delete_flow(file_path)
    """
    
    def __init__(self, root_path: str = "./.gitmem_coding"):
        """Initialize the Coding API."""
        self.store = CodingContextStore(root_path=root_path)
    
    # 1. Create
    def create_flow(self, agent_id: str, file_path: str) -> Dict[str, Any]:
        """
        Create a Code Flow structure for a file.
        Reads file from disk, generates Tree + Index, and stores it.
        """
        return self.store.store_file_context_from_path(
            agent_id=agent_id,
            file_path=file_path,
            storage_mode="flow"
        )

    # 2. Read (Query or ID)
    def get_flow(self, agent_id: str, query: str) -> Dict[str, Any]:
        """
        Retrieve Code Flow.
        
        If query looks like a file path or ID, retrieves the full Flow Tree.
        Otherwise, performs a search using the BST Index and returns relevant paths.
        """
        # Try interpreting query as a file path first
        if "/" in query or "." in query.split("/")[-1]:
             if os.path.exists(query):
                result = self.store.retrieve_file_context(agent_id, query)
                if result.get("status") != "cache_miss":
                    return result
        
        # Determine if it's a UUID (context_id) - simplified check
        if len(query) == 36 and "-" in query:
             # If exact ID match logic existed, it would go here.
             pass

        # Fallback: Search using Global Index (Symbol Search)
        # This handles the "string related queries" requirement.
        results = self.store.search_code_flow(agent_id, query)
        
        return {
            "status": "search_results",
            "query": query,
            "results": results,
            "count": len(results)
        }

    # 3. Update
    def update_flow(self, agent_id: str, file_path: str) -> Dict[str, Any]:
        """
        Update the Code Flow for a file.
        Re-reads, re-indexes, and updates storage.
        """
        # Using store_file_context_from_path handles updates automatically
        return self.store.store_file_context_from_path(
            agent_id=agent_id,
            file_path=file_path,
            storage_mode="flow"
        )
    
    # 4. Delete
    def delete_flow(self, agent_id: str, file_path: str) -> bool:
        """
        Delete the Code Flow for a file.
        """
        return self.store.delete_code_flow(agent_id, file_path)

    # Additional utility (optional, for listing)
    def list_flows(self, agent_id: str, limit: int = 50, offset: int = 0) -> Dict[str, Any]:
        """List all stored code flows."""
        return self.store.list_code_flows(agent_id, limit, offset)
