import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

export interface CadStructuralElement {
  type: string;
  position: string;
  changeable: boolean;
}

export interface CadSpaceMetric {
  room: string;
  ratio: string;
  width: string;
}

export interface CadFlowMetric {
  area: string;
  width: string;
  compliance: boolean;
}

export interface CadAnalysisResult {
  structuralElements: CadStructuralElement[];
  spaceMetrics: CadSpaceMetric[];
  flowMetrics: CadFlowMetric[];
  reportPath?: string;
}

@Injectable({ providedIn: 'root' })
export class CadAnalysisService {
  private readonly API_BASE = '/api/cad-analysis';

  constructor(private http: HttpClient) {}

  /**
   * 通过文件URL触发后端CAD解析
   */
  analyzeByUrl(fileUrl: string, fileName?: string): Observable<CadAnalysisResult> {
    const payload = { fileUrl, fileName };
    return this.http.post<any>(`${this.API_BASE}/analyze-url`, payload).pipe(
      map(res => {
        if (res && res.success && res.data) {
          return res.data as CadAnalysisResult;
        }
        throw new Error('CAD分析返回无效');
      }),
      catchError(err => {
        console.warn('CAD分析服务不可用，回退到本地模拟:', err?.message || err);
        return this.simulateCadAnalysis(fileName || '未知CAD文件');
      })
    );
  }

  /**
   * 本地模拟CAD分析，用于开发联调前
   */
  simulateCadAnalysis(fileName: string): Observable<CadAnalysisResult> {
    const mock: CadAnalysisResult = {
      structuralElements: [
        { type: '承重柱', position: '客厅中央', changeable: false },
        { type: '门窗', position: '南墙', changeable: false }
      ],
      spaceMetrics: [
        { room: '客厅', ratio: '16:9', width: '4.2m' },
        { room: '卧室', ratio: '4:3', width: '3.6m' }
      ],
      flowMetrics: [
        { area: '主通道', width: '1.2m', compliance: true },
        { area: '次通道', width: '0.8m', compliance: false }
      ],
      reportPath: `/reports/cad/${encodeURIComponent(fileName)}.html`
    };
    return of(mock);
  }
}