import { co2 as Co2Model } from "@tgwf/co2";

export type CarbonCalculationSuccess = {
  ok: true;
  checkedUrl: string;
  pageSizeBytes: number;
  pageSizeKb: number;
  estimatedCo2Grams: number;
  estimatedCo2Milligrams: number;
  sustainabilityRating?: string;
};

export type CarbonCalculationFailure = {
  ok: false;
  checkedUrl: string;
  error: string;
  statusCode?: number;
};

export type CarbonCalculationResult = CarbonCalculationSuccess | CarbonCalculationFailure;

type CarbonCalculatorOptions = {
  timeoutMs?: number;
};

const DEFAULT_TIMEOUT_MS = 10000;

export class CarbonCalculatorService {
  private readonly timeoutMs: number;
  private readonly emissionsModel: Co2Model;

  constructor(options: CarbonCalculatorOptions = {}) {
    this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
    this.emissionsModel = new Co2Model({ model: "swd", rating: true });
  }

  async estimatePageCarbon(pageUrl: URL): Promise<CarbonCalculationResult> {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), this.timeoutMs);

    try {
      const response = await fetch(pageUrl.toString(), {
        method: "GET",
        redirect: "follow",
        signal: controller.signal,
        headers: {
          Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        },
        cache: "no-store",
      });

      if (!response.ok) {
        return {
          ok: false,
          checkedUrl: pageUrl.toString(),
          statusCode: response.status,
          error: `Unable to measure this page (HTTP ${response.status})`,
        };
      }

      const html = await response.text();
      const pageSizeBytes = Buffer.byteLength(html, "utf8");
      const result = this.emissionsModel.perByte(pageSizeBytes);

      const estimatedCo2Grams =
        typeof result === "number" ? result : Number(result.total || 0);
      const sustainabilityRating =
        typeof result === "number" ? undefined : result.rating || undefined;

      return {
        ok: true,
        checkedUrl: pageUrl.toString(),
        pageSizeBytes,
        pageSizeKb: pageSizeBytes / 1024,
        estimatedCo2Grams,
        estimatedCo2Milligrams: estimatedCo2Grams * 1000,
        sustainabilityRating,
      };
    } catch (error: unknown) {
      if (error instanceof Error && error.name === "AbortError") {
        return {
          ok: false,
          checkedUrl: pageUrl.toString(),
          error: "The check timed out. Please try again.",
        };
      }

      return {
        ok: false,
        checkedUrl: pageUrl.toString(),
        error: "Unable to reach that website. Please verify the URL and try again.",
      };
    } finally {
      clearTimeout(timeout);
    }
  }
}
