"""
MCP Resource Handlers

Provides access to reports, snapshots, and visualizations via rohkun:// URIs.
"""
import json
from pathlib import Path
from typing import Dict, Any, List


def get_resources() -> List[Dict[str, Any]]:
    """Return list of available MCP resources"""
    return [
        {
            "uri": "rohkun://reports/{project_hash}/{report_filename}",
            "name": "Report Files",
            "description": "Access report files (JSON or text format) by project hash",
            "mimeType": "application/json"
        },
        {
            "uri": "rohkun://snapshots/{project_hash}",
            "name": "Snapshot Index",
            "description": "Access snapshot index data by project hash",
            "mimeType": "application/json"
        },
        {
            "uri": "rohkun://visualization/{project_hash}",
            "name": "Visualization HTML",
            "description": "Access visualization HTML by project hash",
            "mimeType": "text/html"
        }
    ]


def handle_resource_read(uri: str) -> Dict[str, Any]:
    """Handle resource read request"""
    if uri.startswith("rohkun://reports/"):
        return handle_report_resource(uri)
    elif uri.startswith("rohkun://snapshots/"):
        return handle_snapshot_resource(uri)
    elif uri.startswith("rohkun://visualization/"):
        return handle_visualization_resource(uri)
    else:
        raise ValueError(f"Unknown resource URI scheme: {uri}")


def handle_report_resource(uri: str) -> Dict[str, Any]:
    """Handle rohkun://reports/{project_hash}/{report_filename}"""
    # Parse URI: rohkun://reports/RHKN-ABC123/report_20250101_120000.json
    parts = uri.replace("rohkun://reports/", "").split("/")
    if len(parts) != 2:
        raise ValueError(f"Invalid report URI format: {uri}")
    
    project_hash, report_filename = parts
    
    # Find project by hash
    project_path = find_project_by_hash(project_hash)
    if not project_path:
        raise ValueError(f"Project not found: {project_hash}")
    
    # Read report file
    report_file = project_path / ".rohkun" / "reports" / report_filename
    if not report_file.exists():
        raise FileNotFoundError(f"Report not found: {report_filename}")
    
    # Validate it's in .rohkun/reports/
    if ".rohkun/reports/" not in str(report_file):
        raise ValueError("Invalid report path")
    
    # Read content
    with open(report_file, 'r') as f:
        if report_file.suffix == '.json':
            content = json.load(f)
            mime_type = "application/json"
            text = json.dumps(content, indent=2)
        else:
            text = f.read()
            mime_type = "text/plain"
    
    return {
        "contents": [{
            "uri": uri,
            "mimeType": mime_type,
            "text": text
        }]
    }


def handle_snapshot_resource(uri: str) -> Dict[str, Any]:
    """Handle rohkun://snapshots/{project_hash}"""
    # Parse URI: rohkun://snapshots/RHKN-ABC123
    project_hash = uri.replace("rohkun://snapshots/", "")
    
    # Find project by hash
    project_path = find_project_by_hash(project_hash)
    if not project_path:
        raise ValueError(f"Project not found: {project_hash}")
    
    # Read snapshot index
    snapshot_file = project_path / ".rohkun" / "snapshots" / "snapshot_index.json"
    if not snapshot_file.exists():
        raise FileNotFoundError(f"Snapshot index not found for project: {project_hash}")
    
    with open(snapshot_file, 'r') as f:
        content = json.load(f)
    
    return {
        "contents": [{
            "uri": uri,
            "mimeType": "application/json",
            "text": json.dumps(content, indent=2)
        }]
    }


def handle_visualization_resource(uri: str) -> Dict[str, Any]:
    """Handle rohkun://visualization/{project_hash}"""
    # Parse URI: rohkun://visualization/RHKN-ABC123
    project_hash = uri.replace("rohkun://visualization/", "")
    
    # Find project by hash
    project_path = find_project_by_hash(project_hash)
    if not project_path:
        raise ValueError(f"Project not found: {project_hash}")
    
    # Read visualization HTML
    viz_file = project_path / ".rohkun" / "visualization" / "index.html"
    if not viz_file.exists():
        raise FileNotFoundError(f"Visualization not found for project: {project_hash}")
    
    with open(viz_file, 'r') as f:
        content = f.read()
    
    return {
        "contents": [{
            "uri": uri,
            "mimeType": "text/html",
            "text": content
        }]
    }


def find_project_by_hash(project_hash: str) -> Path:
    """Find project directory by project hash"""
    # Search common locations for .rohkun/project.json with matching hash
    search_paths = [
        Path.cwd(),  # Current directory
        Path.cwd().parent,  # Parent directory
        Path.home() / "projects",  # Common project location
    ]
    
    for base_path in search_paths:
        if not base_path.exists():
            continue
        
        # Check if current path is the project
        project_file = base_path / ".rohkun" / "project.json"
        if project_file.exists():
            with open(project_file, 'r') as f:
                project_data = json.load(f)
                if project_data.get("project_hash") == project_hash:
                    return base_path
        
        # Search subdirectories
        for subdir in base_path.iterdir():
            if not subdir.is_dir():
                continue
            
            project_file = subdir / ".rohkun" / "project.json"
            if project_file.exists():
                try:
                    with open(project_file, 'r') as f:
                        project_data = json.load(f)
                        if project_data.get("project_hash") == project_hash:
                            return subdir
                except:
                    continue
    
    return None
