"""
Seed accounting dimensions (Cost Centers and Projects)
"""
from sqlalchemy.orm import Session
from app.models.accounting_dimensions import AccountingDimension, AccountingDimensionValue
import uuid

from .registry import register

@register("dimensions")
def seed_dimensions(db: Session):
    """Seed default accounting dimensions and their values"""

    # Check if dimensions already exist
    existing_dims = {d.code: d for d in db.query(AccountingDimension).all()}

    # 1. COST CENTER / DEPARTMENT Dimension
    if 'DEPT' not in existing_dims:
        dept_dim = AccountingDimension(
            id=str(uuid.uuid4()),
            code='DEPT',
            name='Department',
            description='Organizational departments for cost tracking',
            dimension_type='functional',
            scope='global',
            is_active=True,
            is_required=False,
            allow_multiple_values=False,
            supports_hierarchy=False,
            display_order=1
        )
        db.add(dept_dim)
        db.flush()
        existing_dims['DEPT'] = dept_dim
        print(f"[SEED] Created dimension: DEPT - Department")
    else:
        dept_dim = existing_dims['DEPT']
        print(f"[SEED] Dimension already exists: DEPT")

    # Department/Cost Center Values
    dept_values = [
        {'code': 'SALES', 'name': 'Sales Department', 'description': 'Sales and business development'},
        {'code': 'MKTG', 'name': 'Marketing Department', 'description': 'Marketing and advertising'},
        {'code': 'FIN', 'name': 'Finance Department', 'description': 'Financial management and accounting'},
        {'code': 'OPS', 'name': 'Operations Department', 'description': 'Operations and logistics'},
        {'code': 'IT', 'name': 'IT Department', 'description': 'Information technology and systems'},
        {'code': 'HR', 'name': 'Human Resources', 'description': 'Human resources and personnel'},
        {'code': 'ADMIN', 'name': 'Administration', 'description': 'General administration'},
    ]

    existing_dept_values = {v.code for v in db.query(AccountingDimensionValue).filter_by(dimension_id=dept_dim.id).all()}

    for val_data in dept_values:
        if val_data['code'] not in existing_dept_values:
            dept_val = AccountingDimensionValue(
                id=str(uuid.uuid4()),
                dimension_id=dept_dim.id,
                code=val_data['code'],
                name=val_data['name'],
                description=val_data['description'],
                is_active=True
            )
            db.add(dept_val)
            print(f"[SEED]   Created value: {val_data['code']} - {val_data['name']}")

    # 2. PROJECT Dimension
    if 'PROJ' not in existing_dims:
        proj_dim = AccountingDimension(
            id=str(uuid.uuid4()),
            code='PROJ',
            name='Project',
            description='Projects for tracking project-based revenue and costs',
            dimension_type='project',
            scope='global',
            is_active=True,
            is_required=False,
            allow_multiple_values=False,
            supports_hierarchy=False,
            display_order=2
        )
        db.add(proj_dim)
        db.flush()
        existing_dims['PROJ'] = proj_dim
        print(f"[SEED] Created dimension: PROJ - Project")
    else:
        proj_dim = existing_dims['PROJ']
        print(f"[SEED] Dimension already exists: PROJ")

    # Project Values
    project_values = [
        {'code': 'PROJ001', 'name': 'Project Alpha', 'description': 'Alpha initiative project'},
        {'code': 'PROJ002', 'name': 'Project Beta', 'description': 'Beta development project'},
        {'code': 'PROJ003', 'name': 'Project Gamma', 'description': 'Gamma implementation project'},
        {'code': 'GENERAL', 'name': 'General Operations', 'description': 'Non-project specific activities'},
    ]

    existing_proj_values = {v.code for v in db.query(AccountingDimensionValue).filter_by(dimension_id=proj_dim.id).all()}

    for val_data in project_values:
        if val_data['code'] not in existing_proj_values:
            proj_val = AccountingDimensionValue(
                id=str(uuid.uuid4()),
                dimension_id=proj_dim.id,
                code=val_data['code'],
                name=val_data['name'],
                description=val_data['description'],
                is_active=True
            )
            db.add(proj_val)
            print(f"[SEED]   Created value: {val_data['code']} - {val_data['name']}")

    db.commit()

    # Summary
    total_dims = db.query(AccountingDimension).count()
    total_values = db.query(AccountingDimensionValue).count()
    print(f"[SEED] Dimensions seeded successfully: {total_dims} dimensions, {total_values} values")
