import 'dart:io';
import 'package:yaml/yaml.dart';
import 'models.dart';

class BriefLoader {
  static Future<ProjectBrief> load(String path) async {
    final file = File(path);
    if (!file.existsSync()) {
      throw FileSystemException('project-brief.yaml not found at $path. '
          'Run: cursor_gen --wizard  to create one.');
    }
    final content = await file.readAsString();
    final yaml = loadYaml(content) as YamlMap;

    final project = yaml['project'] as YamlMap;
    final stack = yaml['stack'] as YamlMap;
    final envs = yaml['environments'] as YamlMap? ?? YamlMap();
    final testing = yaml['testing'] as YamlMap? ?? YamlMap();
    final design = yaml['design'] as YamlMap? ?? YamlMap();
    final apiDocs = yaml['api_docs'] as YamlMap? ?? YamlMap();
    final refs = yaml['references'] as YamlMap? ?? YamlMap();
    final appCtx = yaml['app_context'] as YamlMap? ?? YamlMap();
    final features = yaml['features'] as YamlMap? ?? YamlMap();
    final l10n = yaml['localization'] as YamlMap? ?? YamlMap();

    // Parse backends (can be "firebase+rest" shorthand or list)
    final backendRaw = stack['backend']?.toString() ?? 'rest';
    final backends =
        backendRaw.contains('+') ? backendRaw.split('+') : [backendRaw];

    return ProjectBrief(
      projectName: project['name']?.toString() ?? 'MyApp',
      packageId: project['package']?.toString() ?? 'com.example.myapp',
      description: project['description']?.toString() ?? '',
      scale: project['scale']?.toString() ?? 'medium',

      stateManagement: stack['state_management']?.toString() ?? 'riverpod',
      routing: stack['routing']?.toString() ?? 'gorouter',
      architecture: stack['architecture']?.toString() ?? 'feature_first',
      backends: backends.map((b) => b.trim()).toList(),
      auth: stack['auth']?.toString() ?? 'none',

      // Pillar 4: platform + codegen
      platforms: _toStringList(stack['platforms']) ?? ['ios', 'android'],
      codegenTools: _toStringList(stack['codegen']) ?? [],

      flavors: _toStringList(envs['flavors']) ?? ['dev', 'prod'],
      cicd: envs['cicd']?.toString() ?? 'github_actions',

      testingDepth: testing['depth']?.toString() ?? 'unit_widget',
      e2eTool: testing['e2e_tool']?.toString() ?? 'patrol',

      designSource: design['source']?.toString() ?? 'none',
      figmaUrl: design['figma_url']?.toString() ?? '',

      apiDocsFormat: apiDocs['format']?.toString() ?? 'none',
      apiDocsPath: apiDocs['path']?.toString() ?? '',

      referenceRepos: _toStringList(refs['repos']) ?? [],
      localPaths: _toStringList(refs['local_paths']) ?? [],

      featureModules: _toStringList(features['modules']) ?? [],
      specialFeatures: _toStringList(features['special']) ?? [],

      i18nEnabled: l10n['enabled'] as bool? ?? false,
      locales: _toStringList(l10n['locales']) ?? ['en'],

      cursorTemplatesVersion: yaml['cursor_templates_version']?.toString(),
      telemetryOptIn: yaml['telemetry_opt_in'] as bool? ?? false,

      themeVariants: () {
        final t = _toStringList(appCtx['theme_variants']);
        if (t == null || t.isEmpty) return ['light', 'dark'];
        return t;
      }(),
      rolesEnabled: appCtx['roles_enabled'] as bool? ?? false,
      roleNames: _toStringList(appCtx['role_names']) ?? [],
    );
  }

  static List<String>? _toStringList(dynamic value) {
    if (value == null) return null;
    if (value is YamlList) return value.map((e) => e.toString()).toList();
    if (value is List) return value.map((e) => e.toString()).toList();
    if (value is String) return [value];
    return null;
  }
}
