import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import asyncio
from sqlalchemy.future import select
from app.core.database import AsyncSessionLocal
from app.models.dealer_models import FeatureSegmentMap, CustomerSegmentMaster, SpecialFeatureMaster

async def seed_feature_segments():
    async with AsyncSessionLocal() as db:
        try:
            segments_result = await db.execute(select(CustomerSegmentMaster))
            segments = segments_result.scalars().all()
            
            features_result = await db.execute(select(SpecialFeatureMaster))
            features = features_result.scalars().all()
            
            if not segments or not features:
                print("No segments or features found. Please ensure seed_production.py has run first.")
                return

            existing_maps_result = await db.execute(select(FeatureSegmentMap))
            existing_maps = existing_maps_result.scalars().all()
            existing_pairs = {(m.feature_id, m.segment_id) for m in existing_maps}
            
            new_maps = []
            for feature in features:
                for segment in segments:
                    if (feature.feature_id, segment.segment_id) not in existing_pairs:
                        new_maps.append(
                            FeatureSegmentMap(
                                feature_id=feature.feature_id,
                                segment_id=segment.segment_id
                            )
                        )
            
            if new_maps:
                db.add_all(new_maps)
                await db.commit()
                print(f"Successfully mapped {len(new_maps)} feature-segment pairs.")
            else:
                print("All features are already mapped to all segments. Nothing to do.")

        except Exception as e:
            await db.rollback()
            print(f"Error seeding feature segments: {e}")

if __name__ == "__main__":
    asyncio.run(seed_feature_segments())
