import { createModuleLogger } from '../../utils/logger.js';
import { dataStore } from '../data-store/index.js';
import type { SceneTemplate } from '../../types/api.js';

const log = createModuleLogger('template-manager');

export const DEFAULT_TEMPLATES: Omit<SceneTemplate, 'id' | 'createdAt' | 'updatedAt'>[] = [
  // indoor (2)
  {
    name: 'Ev Ortamı',
    category: 'indoor',
    promptTemplate: '{subject}, relaxing at home, {clothing}, soft natural window light, modern living room, {camera}',
    environment: { lighting: 'soft natural window light', timeOfDay: 'afternoon' },
    defaultAspectRatio: '4:3',
  },
  {
    name: 'Yatak Odası',
    category: 'indoor',
    promptTemplate: '{subject}, in a cozy bedroom, {clothing}, warm lamp lighting, elegant bedroom interior, {camera}',
    environment: { lighting: 'warm lamp lighting', timeOfDay: 'evening' },
    defaultAspectRatio: '4:3',
  },
  // outdoor (2)
  {
    name: 'Sahil',
    category: 'outdoor',
    promptTemplate: '{subject}, walking on a tropical beach, {clothing}, golden hour sunlight, ocean waves, {camera}',
    environment: { lighting: 'golden hour sunlight', weather: 'clear sky', timeOfDay: 'sunset' },
    defaultAspectRatio: '16:9',
  },
  {
    name: 'Park Yürüyüşü',
    category: 'outdoor',
    promptTemplate: '{subject}, strolling through a beautiful park, {clothing}, natural daylight, green trees, {camera}',
    environment: { lighting: 'natural daylight', weather: 'sunny', timeOfDay: 'morning' },
    defaultAspectRatio: '16:9',
  },
  // sport (2)
  {
    name: 'Spor Salonu',
    category: 'sport',
    promptTemplate: '{subject}, working out in a modern gym, {clothing}, bright overhead lighting, gym equipment, {camera}',
    environment: { lighting: 'bright overhead lighting', timeOfDay: 'daytime' },
    defaultAspectRatio: '4:3',
  },
  {
    name: 'Yoga Seansı',
    category: 'sport',
    promptTemplate: '{subject}, doing yoga in a serene studio, {clothing}, soft diffused lighting, minimalist studio, {camera}',
    environment: { lighting: 'soft diffused lighting', timeOfDay: 'morning' },
    defaultAspectRatio: '4:3',
  },
  // social (2)
  {
    name: 'Kafe Molası',
    category: 'social',
    promptTemplate: '{subject}, sitting in a cozy cafe, {clothing}, warm ambient lighting, coffee shop interior, {camera}',
    environment: { lighting: 'warm ambient lighting', timeOfDay: 'afternoon' },
    defaultAspectRatio: '4:3',
  },
  {
    name: 'Restoran Akşamı',
    category: 'social',
    promptTemplate: '{subject}, dining at an elegant restaurant, {clothing}, candlelight ambiance, fine dining setting, {camera}',
    environment: { lighting: 'candlelight ambiance', timeOfDay: 'evening' },
    defaultAspectRatio: '4:3',
  },
  // professional (2)
  {
    name: 'Ofis',
    category: 'professional',
    promptTemplate: '{subject}, in a modern office, {clothing}, professional studio lighting, minimalist office, {camera}',
    environment: { lighting: 'professional studio lighting', timeOfDay: 'daytime' },
    defaultAspectRatio: '4:3',
  },
  {
    name: 'İş Toplantısı',
    category: 'professional',
    promptTemplate: '{subject}, in a corporate meeting room, {clothing}, bright conference lighting, glass-walled room, {camera}',
    environment: { lighting: 'bright conference lighting', timeOfDay: 'daytime' },
    defaultAspectRatio: '4:3',
  },
  // nightlife (2)
  {
    name: 'Gece Kulübü',
    category: 'nightlife',
    promptTemplate: '{subject}, at a nightclub, {clothing}, neon and strobe lighting, dark club atmosphere, {camera}',
    environment: { lighting: 'neon and strobe lighting', timeOfDay: 'night' },
    defaultAspectRatio: '9:16',
  },
  {
    name: 'Rooftop Bar',
    category: 'nightlife',
    promptTemplate: '{subject}, at a rooftop bar, {clothing}, city lights at night, skyline view, {camera}',
    environment: { lighting: 'city lights at night', timeOfDay: 'night' },
    defaultAspectRatio: '9:16',
  },
];

export class TemplateManager {
  /**
   * Fill a template's prompt with provided values.
   */
  fillTemplate(template: SceneTemplate, values: Record<string, string>): string {
    let prompt = template.promptTemplate;
    for (const [key, value] of Object.entries(values)) {
      prompt = prompt.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
    }
    return prompt;
  }

  /**
   * Get a template by ID from the data store.
   */
  async getTemplate(id: string): Promise<SceneTemplate | null> {
    return dataStore.getTemplate(id);
  }

  /**
   * List all templates, optionally filtered by category.
   */
  async listTemplates(category?: SceneTemplate['category']): Promise<SceneTemplate[]> {
    const all = await dataStore.listTemplates();
    if (!category) return all;
    return all.filter(t => t.category === category);
  }

  /**
   * Create a new template.
   */
  async createTemplate(input: Omit<SceneTemplate, 'id' | 'createdAt' | 'updatedAt'>): Promise<SceneTemplate> {
    const now = new Date().toISOString();
    const id = input.name.toLowerCase().replace(/\s+/g, '-') + '-' + Date.now();
    const template: SceneTemplate = {
      ...input,
      id,
      createdAt: now,
      updatedAt: now,
    };
    await dataStore.saveTemplate(template);
    return template;
  }

  /**
   * Update an existing template.
   */
  async updateTemplate(id: string, updates: Partial<SceneTemplate>): Promise<SceneTemplate> {
    const existing = await dataStore.getTemplate(id);
    if (!existing) throw new Error('Template not found');
    const updated: SceneTemplate = {
      ...existing,
      ...updates,
      id: existing.id,
      createdAt: existing.createdAt,
      updatedAt: new Date().toISOString(),
    };
    await dataStore.saveTemplate(updated);
    return updated;
  }

  /**
   * Delete a template by ID.
   */
  async deleteTemplate(id: string): Promise<boolean> {
    return dataStore.deleteTemplate(id);
  }

  /**
   * Initialize default templates if none exist.
   */
  async initDefaults(): Promise<void> {
    const existing = await dataStore.listTemplates();
    if (existing.length > 0) return;

    const now = new Date().toISOString();
    for (const tpl of DEFAULT_TEMPLATES) {
      const template: SceneTemplate = {
        ...tpl,
        id: tpl.name.toLowerCase().replace(/\s+/g, '-'),
        createdAt: now,
        updatedAt: now,
      };
      await dataStore.saveTemplate(template);
    }
    log.info(`Initialized ${DEFAULT_TEMPLATES.length} default templates`);
  }
}

export const templateManager = new TemplateManager();
