from .client import PiDataMetrics
from .parsers import PiParsers
from .exporter import PiExporter
import datetime

class PiReportManager(PiDataMetrics):
    """
    High-level manager that combines API fetching, parsing, and exporting.
    Inherits from PiDataMetrics so it can access API methods directly.
    """

    def _resolve_workspaces(self, ids_str=None, name_pattern=None):
        """Helper to find workspace IDs based on input."""
        all_ws = self.get_workspaces()
        targets = {}

        if ids_str and ids_str.strip():
            target_ids = [int(x.strip()) for x in ids_str.split(',') if x.strip().isdigit()]
            for ws in all_ws:
                if ws['id'] in target_ids:
                    targets[ws['id']] = ws['name']
        elif name_pattern:
            for ws in all_ws:
                if ws.get('tracked') and name_pattern.lower() in ws['name'].lower():
                    targets[ws['id']] = ws['name']
        return targets

    def run_volume_report(self, filename, workspace_ids=None, workspace_name=None):
        """
        Full workflow: Find WS -> Get Volume -> Map STGs -> Save CSV
        """
        targets = self._resolve_workspaces(workspace_ids, workspace_name)
        if not targets:
            print("No workspaces found.")
            return

        all_rows = []
        print(f"Starting Volume Report for {len(targets)} workspaces...")

        for ws_id, ws_name in targets.items():
            print(f"Processing: {ws_name}...")
            # 1. Fetch
            vol_data = self.get_bulk_volume(ws_id)
            stgs = self.get_stgs(ws_id)
            
            # 2. Parse
            for stg in stgs:
                terms = self.get_search_terms(ws_id, stg['id'])
                rows = PiParsers.parse_volume_data(vol_data, stg['name'], terms, ws_name)
                all_rows.extend(rows)

        # 3. Export
        PiExporter.to_csv(all_rows, filename)

    def run_serp_report(self, data_sources, output_mode='csv', bq_config=None, filename=None, manual_duplication=None):
        """
        Full workflow: Loop Sources -> Get SERP -> Map Categories -> Save
        data_sources format: [[Market, WS_ID, WS_Name, SE_ID, SE_Name], ...]
        """
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        print(f"Starting SERP Report for {yesterday}...")
        
        all_rows = []

        for source in data_sources:
            market, w_id, w_name, se_id, se_name = source
            print(f"Fetching: {w_name} ({se_name})...")

            # 1. Fetch
            raw_data = self.get_bulk_serp_data(w_id, se_id, yesterday)
            cat_map = PiParsers.build_category_map(self, w_id)

            # 2. Parse
            rows = PiParsers.parse_serp_response(
                raw_data, market, w_name, se_name, yesterday, cat_map, manual_duplication
            )
            all_rows.extend(rows)

        # 3. Export
        if output_mode == 'bigquery' and bq_config:
            PiExporter.to_bigquery(all_rows, bq_config['project'], bq_config['dataset'], bq_config['table'])
        else:
            PiExporter.to_csv(all_rows, filename or "serp_output.csv")