# Songify Integration

This directory contains the TypeScript implementation of the Songify video generation integration, migrated from the original JavaScript React app.

## Overview

The Songify integration allows users to create AI-generated music videos from uploaded video files. It supports multiple music genres, real-time status polling, and project management with localStorage persistence.

## Architecture

### Core Components

1. **Types** (`src/types/songify.ts`)
   - `SongifyProject`: Main project data structure
   - `SongifyVideo`: Individual video within a project
   - `SongifyProjectStatus`: Enum for project states
   - API request/response interfaces

2. **Configuration** (`src/config/songify.ts`)
   - API endpoints (Modal, Suno)
   - Validation limits
   - Music styles
   - Timing constants

3. **Hooks**
   - `useSongify`: Main hook combining all functionality
   - `useSongifyProjects`: localStorage-based project management
   - `useSongifyActions`: API calls and mutations
   - `useSongifyStatusPolling`: Real-time status updates

4. **UI Components**
   - `SongifyPageClient`: Simple test interface

## Usage

### Basic Usage

```typescript
import { useSongify } from '@/hooks/songify';

function MyComponent() {
  const songify = useSongify();

  const handleCreateProject = async () => {
    await songify.createProject({
      description: 'My test project',
      s3FileName: 'video.mp4',
      selectedGenres: ['pop', 'rock'],
      numGenerations: 4,
      enableLyricOverlay: false,
    });
  };

  return (
    <div>
      <h1>Projects: {songify.projects.length}</h1>
      <button onClick={handleCreateProject} disabled={songify.isCreating}>
        Create Project
      </button>
      
      {songify.projects.map(project => (
        <div key={project.id}>
          <h3>{project.name}</h3>
          <p>Status: {project.status}</p>
          <p>Videos: {project.videos.length}</p>
        </div>
      ))}
    </div>
  );
}
```

### Advanced Usage

```typescript
import { 
  useSongifyProjects, 
  useSongifyActions, 
  useSongifyStatusPolling 
} from '@/hooks/songify';

function AdvancedComponent() {
  const projects = useSongifyProjects();
  const actions = useSongifyActions();
  const [selectedProject, setSelectedProject] = useState(null);
  
  // Poll status for selected project
  const polling = useSongifyStatusPolling({
    songifyId: selectedProject?.songifyId,
    initialStatus: selectedProject?.status,
    onStatusUpdate: projects.handleStatusUpdate,
    isProjectStale: projects.isProjectStale,
  });

  // Custom project creation with error handling
  const handleCreateProject = async (options) => {
    try {
      const result = await actions.createProject.mutateAsync(options);
      projects.addProject(result.project);
      setSelectedProject(result.project);
    } catch (error) {
      console.error('Failed to create project:', error);
    }
  };

  return (
    <div>
      {/* Your custom UI */}
    </div>
  );
}
```

## Key Features

### 1. Project Management
- Create new projects with customizable settings
- Update project metadata (name, description)
- Delete individual or all projects
- Regenerate projects with incremented names
- localStorage persistence across sessions

### 2. Status Polling
- Real-time status updates via API polling
- Automatic polling termination on completion/failure
- Stale project detection (15-minute timeout)
- Error handling for network issues

### 3. API Integration
- Support for both V1 (Modal) and V2 (Studio) APIs
- Presigned URL generation for file uploads
- Proper error handling and retry logic
- Optimistic updates with rollback

### 4. Video Generation
- Multiple genre support
- Configurable generation count
- UUID-based video tracking
- Lyric overlay option

## Project Status Flow

```
PENDING → PROCESSING_UPLOAD → GENERATING_REMIXES → GENERATING_VIDEOS → COMPLETED
                                                                    ↘ FAILED_EXPECTED
                                                                    ↘ FAILED_SYSTEM
                                                                    ↘ CANCELLED
```

## Configuration

### Limits
- Max file size: 100MB
- Video duration: 10-150 seconds
- Max generations: 20 per project
- Polling interval: 2 seconds
- Stale timeout: 15 minutes

## Testing

Visit `/songify` to access the test interface, which provides:
- Project creation form
- Project list with status indicators
- Edit/delete/regenerate actions
- Real-time status updates
- Debug information

## Migration Notes

This TypeScript implementation maintains compatibility with the original JavaScript app while adding:
- Strong typing throughout
- Better error handling
- Improved state management
- React Query integration
- Modular architecture

## Recent Updates

✅ **File Upload Integration**: Added complete Uppy-based file upload with video validation
✅ **Comprehensive UI**: Created full-featured UI matching the original JavaScript app
✅ **TypeScript Migration**: Complete type safety throughout the codebase
✅ **React Query Integration**: Proper state management and caching
✅ **Real-time Status Polling**: Automatic status updates with proper termination

## TODO

1. Implement proper environment detection
2. Add video playback components with fullscreen support
3. Enhance error messaging and user feedback
4. Add loading states for better UX
5. Implement proper authentication
6. Add analytics/tracking
7. Update V2 API URL for production
8. Add comprehensive testing 