/**
 * ProjectInitializer - Creates .air/shared and .air/local directory trees
 *
 * Implements DD §6.1 "ProjectInitializer.scaffold(root, options)"
 * This is a minimal implementation. Full implementation requires Node.js types.
 *
 * @module packages/runtime/src/project/ProjectInitializer
 */

import { mkdirSync, writeFileSync, existsSync } from 'fs'
import { join } from 'path'
import { randomUUID } from 'crypto'

import type { ProjectContext, ProjectInitOptions } from '@aircoding/contracts'

const AIR_DIR = '.air'
const SHARED_DIR = 'shared'
const LOCAL_DIR = 'local'
const SESSIONS_DIR = 'sessions'
const ARTIFACTS_DIR = 'artifacts'
const PROJECT_FILE = 'project.json'

/**
 * ProjectInitializer creates the .air directory structure and generates project_id
 */
export class ProjectInitializer {
  initialize(projectRoot: string, options?: ProjectInitOptions): ProjectContext {
    const airRoot = join(projectRoot, AIR_DIR)
    const sharedRoot = join(airRoot, SHARED_DIR)
    const localRoot = join(airRoot, LOCAL_DIR)

    const projectId = this.generateProjectId()

    this.createDirectories(projectRoot, sharedRoot, localRoot)
    this.writeProjectJson(sharedRoot, projectId, options)

    return {
      project_id: projectId,
      project_root: projectRoot,
      air_root: airRoot,
      shared_root: sharedRoot,
      local_root: localRoot,
      schema_version: 1,
    }
  }

  private generateProjectId(): string {
    return `proj_${randomUUID().replace(/-/g, '').slice(0, 24)}`
  }

  private createDirectories(_projectRoot: string, sharedRoot: string, localRoot: string): void {
    mkdirSync(join(sharedRoot), { recursive: true })
    mkdirSync(join(localRoot, SESSIONS_DIR), { recursive: true })
    mkdirSync(join(localRoot, SESSIONS_DIR, 'tmp', ARTIFACTS_DIR), { recursive: true })
  }

  private writeProjectJson(sharedRoot: string, projectId: string, options?: ProjectInitOptions): void {
    const projectJsonPath = join(sharedRoot, PROJECT_FILE)

    if (existsSync(projectJsonPath) && !options?.force) {
      return
    }

    const projectJson = {
      project_id: projectId,
      schema_version: 1,
      title: options?.title ?? 'Untitled Project',
      created_at: new Date().toISOString(),
    }

    writeFileSync(projectJsonPath, JSON.stringify(projectJson, null, 2) + '\n', 'utf-8')
  }
}

export function createProjectInitializer(): ProjectInitializer {
  return new ProjectInitializer()
}