from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import os
from typing import List, Optional

app = FastAPI(
    title="Filesystem MCP API",
    description="API for file system operations.",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

class FileContent(BaseModel):
    content: str

class FileInfo(BaseModel):
    name: str
    type: str # "file" or "directory"

@app.get("/files/{path:path}", response_model=List[FileInfo])
async def list_directory(path: str = "."):
    """
    List contents of a directory.
    """
    try:
        full_path = os.path.join("/workspace", path) # Assuming /workspace is the root for MCP
        if not os.path.isdir(full_path):
            raise HTTPException(status_code=404, detail="Directory not found")
        
        items = []
        for item in os.listdir(full_path):
            item_path = os.path.join(full_path, item)
            item_type = "directory" if os.path.isdir(item_path) else "file"
            items.append(FileInfo(name=item, type=item_type))
        return items
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/file/{path:path}", response_model=FileContent)
async def read_file(path: str):
    """
    Read contents of a file.
    """
    try:
        full_path = os.path.join("/workspace", path)
        if not os.path.isfile(full_path):
            raise HTTPException(status_code=404, detail="File not found")
        
        with open(full_path, "r", encoding="utf-8") as f:
            content = f.read()
        return FileContent(content=content)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/file/{path:path}", response_model=dict)
async def write_file(path: str, file_content: FileContent):
    """
    Write content to a file.
    """
    try:
        full_path = os.path.join("/workspace", path)
        os.makedirs(os.path.dirname(full_path), exist_ok=True)
        with open(full_path, "w", encoding="utf-8") as f:
            f.write(file_content.content)
        return {"message": f"File {path} written successfully."}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/directory/{path:path}", response_model=dict)
async def create_directory(path: str):
    """
    Create a new directory.
    """
    try:
        full_path = os.path.join("/workspace", path)
        os.makedirs(full_path, exist_ok=True)
        return {"message": f"Directory {path} created successfully."}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))