from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from market_api.core.config import AppSettings
from market_api.db.postgres import connect, replace_table
from market_api.importer.mappings import ALL_SHEET_SPECS, SheetSpec
from market_api.importer.workbook import iter_sheet_records, validate_monthly_workbook


@dataclass(frozen=True)
class TableImportSummary:
    sheet_name: str
    table_name: str
    rows: int


@dataclass(frozen=True)
class ImportSummary:
    source_filename: str
    schema: str
    tables: tuple[TableImportSummary, ...]

    @property
    def total_rows(self) -> int:
        return sum(table.rows for table in self.tables)


def import_monthly_excel(
    settings: AppSettings,
    workbook_path: str | Path,
    source_filename: str | None = None,
    specs: tuple[SheetSpec, ...] = ALL_SHEET_SPECS,
) -> ImportSummary:
    path = Path(workbook_path)
    if not path.exists():
        raise FileNotFoundError(f"Excel 文件不存在：{path}")
    validate_monthly_workbook(path, specs)
    table_summaries: list[TableImportSummary] = []
    with connect(settings.database) as conn:
        for spec in specs:
            count = replace_table(
                conn,
                settings.schema,
                spec,
                iter_sheet_records(path, spec),
            )
            table_summaries.append(
                TableImportSummary(
                    sheet_name=spec.sheet_name,
                    table_name=spec.table_name,
                    rows=count,
                )
            )
    return ImportSummary(
        source_filename=source_filename or path.name,
        schema=settings.schema,
        tables=tuple(table_summaries),
    )


def is_allowed_upload_filename(filename: str) -> bool:
    return bool(filename) and Path(filename).suffix.lower() == ".xlsx"
